Files.write: Writing Collections to Files
What You'll Learn
You'll learn how to write collections of strings directly to files using Files.write, creating or overwriting files in a single atomic operation.
The Core Idea
The Files.write method provides a convenient way to write an Iterable<? extends CharSequence> (like a List<String>) directly to a file. This is the complement to Files.readAllLines — just as you can read a file into a list of strings, you can write a list of strings back to a file.
Think of it like dumping a bucket of labeled cards into a filing cabinet drawer: each string in your collection becomes one line in the file, and the entire operation happens in one atomic action.
How It Works
Path outputPath = Paths.get("output.txt");
List<String> lines = List.of(
"First line",
"Second line",
"Third line"
);
Files.write(outputPath, lines);
This creates output.txt (or overwrites it if it exists) with three lines. The method automatically adds platform-appropriate line separators between elements.
You can specify encoding and file creation options:
Files.write(outputPath, lines, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
Common Use Cases
// Collect processed data and write it out
List<String> logEntries = new ArrayList<>();
logEntries.add("Log entry 1");
logEntries.add("Log entry 2");
Files.write(Paths.get("log.txt"), logEntries);
The operation is atomic — the file is either fully written or not written at all, preventing partial writes from corrupted files.
Key Takeaway: Files.write(path, collection) writes an entire collection of strings to a file, with each element becoming a line, creating or overwriting the file atomically in one convenient operation.