I/O beginner

Writing files

Write a String to a file with one line.

✕ Java 8
try (BufferedWriter bw =
    new BufferedWriter(
        new FileWriter("out.txt"))) {
    bw.write(content);
}
✓ Java 11+
Files.writeString(
    Path.of("out.txt"),
    content
);
📏

One line

No writer wrapping or try-with-resources needed.

🛡️

Safe defaults

UTF-8 encoding, proper file handle cleanup.

🔧

Options

Pass OpenOption flags for append, create, etc.

Old Approach
FileWriter + BufferedWriter
Modern Approach
Files.writeString()
Since JDK
11
Difficulty
beginner
Writing files
Available

Widely available since JDK 11 (Sept 2018)

How it works

Files.writeString() writes content to a file with UTF-8 encoding by default. Options can be passed for appending, creating, etc.

Share 𝕏 🦋 in