Sub topic 7
Writing and Appending Whole Files
Assume you know basic Java classes, checked exceptions, and try/catch. This chapter uses Java 11 or later.
The Files class provides convenient methods for writing small or moderate text files. A Path identifies the file location. Files.writeString writes text, while Files.write can write bytes or a list of text lines.
Writing text and replacing existing content
This call creates a file if it does not exist:
Files.writeString(file, "Hello\n");If the file already exists, Java replaces its contents by default. The method uses UTF-8 unless you select another charset. You can make the encoding explicit:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteFile {
public static void main(String[] args) throws IOException {
Path file = Path.of("notes.txt");
Files.writeString(
file,
"first line\nsecond line\n",
StandardCharsets.UTF_8
);
}
}writeString can throw IOException, a checked exception that represents a failure while accessing the file system. The example declares that exception with throws.
Choosing open options
An open option controls how Java opens a file. The most common options are:
| Option | Effect |
|---|---|
| `CREATE` | Create the file when it does not exist |
| `TRUNCATE_EXISTING` | Remove existing contents before writing |
| `APPEND` | Write after the existing contents |
| `CREATE_NEW` | Create a new file, but fail if it already exists |
The simple overload uses create-and-replace behavior. Pass options when you need different behavior.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class AppendFile {
public static void main(String[] args) throws IOException {
Path log = Path.of("app.log");
Files.writeString(
log,
"application started\n",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
}
}With CREATE and APPEND, the first run creates the file. Later runs add another line instead of deleting earlier lines. Include a newline yourself when each entry should occupy its own line.
The main choice is whether the file represents a complete current value or a growing record. Configuration output usually replaces old content. Logs often append.
How the options change the result
Common errors
CREATE_NEW throws FileAlreadyExistsException when the target exists. A missing parent directory can cause NoSuchFileException. Neither CREATE nor CREATE_NEW creates parent directories. Create them first when needed:
Files.createDirectories(Path.of("out"));
Files.writeString(Path.of("out", "report.txt"), "complete\n");Use try/catch when the application needs to recover or show a useful message. Use try-with-resources for readers and writers that remain open, but writeString opens and closes its file internally.
Exercise
Which options create a missing file and append a new line without deleting existing content?
Show answer
Use StandardOpenOption.CREATE and StandardOpenOption.APPEND.