Sub topic 2
Controlling How Files Are Opened
Assume Java 11 or later, basic Java classes, List and Stream, and familiarity with checked exceptions and try-with-resources. The java.nio.file API uses Path to identify a location and Files to perform file operations.
Choosing Open Options
Files.writeString creates a file if needed and replaces existing content by default. StandardOpenOption constants change this behavior.
| Option | Effect |
|---|---|
| `CREATE` | Create the file if it does not exist |
| `APPEND` | Write after existing content |
| `TRUNCATE_EXISTING` | Remove existing content before writing |
To append, use CREATE and APPEND together:
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);
}
}Without APPEND, a write usually truncates the file. Without CREATE, an operation on a missing file can fail.
Buffered Readers and Writers
For larger text files, use a buffered reader or writer to process data incrementally. A buffer reduces the number of operating-system calls. Always provide a charset when the file encoding matters.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyUpperCase {
public static void main(String[] args) throws IOException {
Path input = Path.of("input.txt");
Path output = Path.of("output.txt");
try (BufferedReader reader =
Files.newBufferedReader(input, StandardCharsets.UTF_8);
BufferedWriter writer =
Files.newBufferedWriter(output, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line.toUpperCase());
writer.newLine();
}
}
}
}Try-with-resources closes both objects even when an I/O error occurs.
Streaming Lines with `Files.lines`
Files.lines returns a lazy Stream<String>. It does not load every line into memory, but it keeps the file open while the stream is being used.
try (var lines = Files.lines(Path.of("notes.txt"))) {
long matches = lines.filter(line -> line.startsWith("s"))
.count();
System.out.println(matches);
}Exercise
Which options append text to a file and create it when missing?
Show answer
Use StandardOpenOption.CREATE and StandardOpenOption.APPEND.