Sub topic 7
Writing and Appending Whole Files
This chapter assumes you can build a Path, know what Files.readString does, and understand checked exceptions and try/catch. You also need to know that a charset maps characters to bytes. Here you will write whole files in one call, choose between truncating and appending, and avoid the common mistakes that come with each choice.
The write methods
The Files class has three one-call methods for writing a complete file:
| Method | Input | Default encoding |
|---|---|---|
| `Files.writeString(Path, CharSequence, OpenOption...)` | A string | UTF-8 |
| `Files.write(Path, Iterable<? extends CharSequence>, OpenOption...)` | Lines of text | UTF-8 |
| `Files.write(Path, byte[], OpenOption...)` | Raw bytes | None (bytes are written as given) |
writeString was added in Java 11. The line-based write and the byte-based write have existed since Java 7. Each method opens the file, writes everything, and closes the file, even if an exception occurs. You do not need try-with-resources for these calls.
Default behavior: create or truncate
If you pass no options, the write methods behave as if you had passed CREATE, TRUNCATE_EXISTING and WRITE. The file is created if it is missing. If it already exists, its old content is discarded before the new content is written.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class WriteDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(file, "first\nsecond\n");
System.out.println(Files.readString(file).length());
Files.writeString(file, "only this\n");
System.out.println(Files.readAllLines(file));
Files.write(file, List.of("alpha", "beta", "gamma"));
System.out.println(Files.readAllLines(file));
}
}The second call replaces the two lines from the first call. The third call shows the Iterable form: it writes each element followed by the platform line separator (\n on Linux and macOS, \r\n on Windows). writeString adds nothing. If you want a trailing newline, include it in the string.
A common bug is to call writeString in a loop, expecting each call to add to the file. Every call truncates, so only the last value survives.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class LoopBug {
public static void main(String[] args) throws IOException {
Path file = Path.of("loop.txt");
for (int i = 1; i <= 3; i++) {
Files.writeString(file, "line " + i + "\n");
}
System.out.println(Files.readString(file));
}
}This prints only line 3.
Choosing options
When you pass any options, they replace the defaults completely. The defaults are not merged with yours. This is the source of most surprises with these methods.
| Options passed | Missing file | Existing file |
|---|---|---|
| none | Created | Truncated, then written |
| `CREATE` | Created | Overwritten from the start, but not truncated (see the warning below) |
| `CREATE, APPEND` | Created | New data added at the end |
| `CREATE_NEW` | Created | `FileAlreadyExistsException` |
| `APPEND` | `NoSuchFileException` | New data added at the end |
| `CREATE, TRUNCATE_EXISTING` | Created | Truncated, then written |
The write methods add WRITE for you if you leave it out, so you do not need to pass it. APPEND implies writing, and you cannot combine APPEND with TRUNCATE_EXISTING or READ. Doing so throws IllegalArgumentException.
Appending
To add to the end of a file, pass CREATE and APPEND. Without CREATE, the call fails if the file does not exist yet.
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 this program three times and app.log contains three started lines. On most operating systems, append mode positions each write at the end of the file at the moment of the write. The Javadoc says that whether this is atomic with respect to other writers is system-dependent, so do not rely on it to keep lines from different processes from interleaving. If several processes must write one log, use a logging library or file locking.
Exclusive creation with CREATE_NEW
CREATE_NEW creates the file only if it does not exist, and the check and the creation happen as one atomic step. This makes it a safe way to claim a file name, for example for a lock marker or a one-time output.
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 file = Path.of("report.txt");
try {
Files.writeString(file, "v1\n", StandardOpenOption.CREATE_NEW);
System.out.println("Created");
} catch (FileAlreadyExistsException e) {
System.out.println("Already exists: " + e.getFile());
}
}
}Checking Files.exists(file) and then writing is weaker. Another process can create the file between the check and the write. CREATE_NEW removes that gap.
Charsets when writing
writeString and the line-based write use UTF-8 unless you pass a charset. Both accept the charset as the argument before the options:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class CharsetWrite {
public static void main(String[] args) throws IOException {
Path file = Path.of("latin.txt");
Files.writeString(file, "café\n", StandardCharsets.ISO_8859_1);
Files.write(file, List.of("naïve", "résumé"), StandardCharsets.ISO_8859_1,
java.nio.file.StandardOpenOption.APPEND);
System.out.println(Files.size(file));
}
}In ISO-8859-1, every character here is one byte, so the file is smaller than the same text in UTF-8, where é takes two bytes. If you read this file back with the default UTF-8 reader, readString throws MalformedInputException. Always use the same charset for writing and reading.
When a character cannot be represented in the target charset, such as € in US-ASCII, the string-based methods throw UnmappableCharacterException (a subclass of CharacterCodingException, which is an IOException). They do not silently substitute ?.
Writing bytes
Use the byte-array form for binary data, or when you have already encoded the text yourself:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ByteWrite {
public static void main(String[] args) throws IOException {
byte[] data = {0x50, 0x4B, 0x03, 0x04};
Files.write(Path.of("header.bin"), data);
System.out.println(Files.size(Path.of("header.bin")));
}
}No charset is involved, and the file contains exactly those four bytes.
Failure modes and limits
- Missing parent directory. Writing to
out/report.txtwhenoutdoes not exist throwsNoSuchFileException. Create it first withFiles.createDirectories(path.getParent()). Note thatgetParent()returnsnullfor a bare name likePath.of("notes.txt"). - Permissions. A read-only file or directory raises
AccessDeniedException. - Directories. Writing to a path that is a directory fails with an
IOException. - Memory. The whole content must already exist in memory before the call. For large or generated output, use a buffered writer, which the next chapter covers.
- Crashes mid-write. Truncation happens before the new content is written. If the program stops between the two steps, the file can be empty or partial. A later chapter shows the temporary-file pattern that avoids this.
- Symbolic links. By default, writing to a symbolic link writes to its target.
NOFOLLOW_LINKSchanges how links are treated in some operations, but check the Javadoc for the behavior you need.
Choosing between the forms
Use writeString for text you already hold as one string, such as a JSON document or a rendered report. Use write with an Iterable when you have a list of lines and want line separators added for you. Use the byte form for binary content. Use CREATE plus APPEND for logs and journals that grow over time, and CREATE_NEW when overwriting would be a mistake.
Exercise
A program runs Files.writeString(path, "ab", StandardOpenOption.CREATE) on an existing file that contains 12345. What does the file contain afterward, and which options would make it contain exactly ab?
Show answer
The file contains ab345. CREATE alone does not truncate, so only the first two bytes are overwritten. Passing StandardOpenOption.CREATE together with StandardOpenOption.TRUNCATE_EXISTING, or passing no options at all, produces exactly ab.
Exercise
You want a program to add one timestamp line to audit.log on each run, creating the file on the first run. Which options do you pass to Files.writeString, and what happens if you pass only StandardOpenOption.APPEND?
Show answer
Pass StandardOpenOption.CREATE and StandardOpenOption.APPEND. With only APPEND, the first run throws NoSuchFileException because the file does not exist and nothing asks for it to be created.