Sub topic 6
Controlling how files are opened
This chapter assumes you can build a Path, call Files.writeString and Files.readString, and handle a checked IOException. It covers the options you pass to Files methods to change how a file is opened, and the errors those options can cause.
What an open option is
Every write method in java.nio.file.Files opens the file before it writes. An open option is a flag that tells the file system how to open it. Is the file created if it is missing? Is existing content kept or erased? Should the call fail if the file already exists?
Options are passed as trailing varargs. Their type is OpenOption, an interface. The enum StandardOpenOption implements it and holds the values you will use most. LinkOption.NOFOLLOW_LINKS also implements it, but this chapter covers only StandardOpenOption.
The options you will use
| Option | Meaning |
|---|---|
| `READ` | Open for reading. |
| `WRITE` | Open for writing. |
| `APPEND` | Every write goes to the end of the file. |
| `TRUNCATE_EXISTING` | If the file exists and is opened for writing, cut its length to zero. |
| `CREATE` | Create the file if it does not exist. Otherwise open the existing file. |
| `CREATE_NEW` | Create the file, and fail if it already exists. |
| `DELETE_ON_CLOSE` | Try to delete the file when the stream or channel closes. |
| `SYNC` | Write both content and metadata to the storage device on every update. |
| `DSYNC` | Write content to the storage device on every update. |
SPARSE also exists. It is a hint for creating sparse files, and most programs never need it.
The defaults
If you pass no options to a write method, you get this set:
CREATETRUNCATE_EXISTINGWRITE
This is why Files.writeString(path, text) creates a missing file and also erases the old content of an existing one. It applies to Files.write, Files.writeString, Files.newOutputStream and Files.newBufferedWriter when called without options.
Read methods default to READ. Methods such as Files.readString, Files.readAllLines and Files.lines take no options at all. Options matter mainly on the write side, and on Files.newInputStream and Files.newByteChannel.
Explicit options replace the defaults
The point people miss most often is that your options replace the defaults. They do not add to them. Once you pass any option, CREATE and TRUNCATE_EXISTING are no longer implied. The write methods always add WRITE for you.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendNoCreate {
public static void main(String[] args) throws IOException {
Path log = Path.of("never-created.log");
Files.deleteIfExists(log);
try {
Files.writeString(log, "hello\n", StandardOpenOption.APPEND);
} catch (NoSuchFileException e) {
System.out.println("Missing, so APPEND alone failed: " + e.getFile());
}
}
}APPEND alone does not create the file, so this throws NoSuchFileException. To append and create when needed, pass both options.
Appending
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendDemo {
public static void main(String[] args) throws IOException {
Path log = Path.of("app.log");
Files.writeString(log, "started\n",
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
}Run it three times and app.log holds three started lines. Each call opens the file, writes at the end, and closes it. For a loop that writes many lines, open one writer instead of calling Files.writeString repeatedly. The buffered methods accept the same options.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendMany {
public static void main(String[] args) throws IOException {
Path log = Path.of("app.log");
try (BufferedWriter writer = Files.newBufferedWriter(log, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
for (int i = 1; i <= 3; i++) {
writer.write("event " + i);
writer.newLine();
}
}
}
}Note the argument order: the charset comes before the options.
Creating a file only if it is new
CREATE silently reuses an existing file. When overwriting would be a bug, use CREATE_NEW. The check for existence and the creation happen as one operation in the file system, so two programs cannot both succeed.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class CreateNewDemo {
public static void main(String[] args) throws IOException {
Path lock = Path.of("job.lock");
try {
Files.writeString(lock, "owner=pid-1\n", StandardOpenOption.CREATE_NEW);
System.out.println("Created, this process owns the lock");
} catch (FileAlreadyExistsException e) {
System.out.println("Another run already created " + e.getFile());
}
}
}The first run prints the first message. Until you delete job.lock, later runs print the second.
Do not write Files.exists(path) followed by a write when you want "create only if absent". Another process can create the file between the two calls. CREATE_NEW closes that gap. If both CREATE and CREATE_NEW are given, CREATE_NEW wins.
Truncate versus overwrite
TRUNCATE_EXISTING empties an existing file when it is opened. The default set includes it, so a plain writeString replaces the old content. If you open a file for WRITE without truncating, writing starts at position 0 and overwrites bytes in place. A shorter text leaves the tail of the old content behind.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class TailDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("tail.txt");
Files.writeString(file, "abcdefgh");
Files.writeString(file, "XY", StandardOpenOption.WRITE);
System.out.println(Files.readString(file));
}
}This prints XYcdefgh. Almost nobody wants that result for text files, which is a reason to leave the defaults alone unless you have a specific need.
Combinations that are rejected
Some combinations make no sense, and the file system throws IllegalArgumentException before touching the file.
APPENDwithTRUNCATE_EXISTING: you cannot both keep the content and erase it.READwithAPPEND: appending is a write-only mode.READpassed toFiles.newOutputStream,Files.writeorFiles.writeString, because those methods only write.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class BadOptions {
public static void main(String[] args) throws IOException {
try {
Files.writeString(Path.of("x.txt"), "data",
StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}IllegalArgumentException is unchecked, so the compiler will not warn you. It signals a programming error. Fix the options and do not catch it in production code.
Durability and temporary files
SYNC and DSYNC ask the operating system to push each write to the storage device before the call returns. They protect data against a power loss, at a large cost in speed. Use them for small, important writes such as a journal entry, not for bulk output.
DELETE_ON_CLOSE suits scratch files. Pair it with CREATE_NEW and a reading and writing channel. The delete is best effort. If the JVM crashes, the file may stay behind.
Common mistakes
- Expecting
APPENDto create a missing file. AddCREATE. - Passing
TRUNCATE_EXISTINGtogether withAPPEND. - Writing to a path with no options when the file holds data you want to keep. The default truncates it.
- Checking
Files.existsbefore writing instead of usingCREATE_NEW. - Putting options before the charset in
newBufferedWriter. The compiler rejects this.
Exercise
You call Files.writeString(Path.of("audit.log"), "entry\n", StandardOpenOption.APPEND) and audit.log does not exist yet. What happens, and which single option would you add so the call creates the file on the first run and appends on later runs?
Show answer
The call throws NoSuchFileException, because explicit options replace the defaults and APPEND alone does not create a file. Adding StandardOpenOption.CREATE fixes it: the file is created when missing and appended to when it exists.
Exercise
Two copies of a program start at the same moment, and exactly one of them must be allowed to create report.lock. Why is checking Files.notExists and then writing the file unsafe, and which option should you use instead?
Show answer
Both programs can pass the notExists check before either one writes, so both believe they own the lock. Use StandardOpenOption.CREATE_NEW. The existence check and the creation are one atomic step, so only one program succeeds and the other gets FileAlreadyExistsException.