Web Analytics

Writing Files

Intermediate ~15 min read

Writing content to files is as important as reading. Java provides BufferedWriter and FileWriter for efficient text output.

Using BufferedWriter

Allows writing text to a character-output stream, buffering characters to provide for the efficient writing of single characters, arrays, and strings.

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World");
    bw.newLine();
    bw.write("Java File I/O is great.");
} catch (IOException e) {
    e.printStackTrace();
}

Appending to a File

To append instead of overwrite, pass true to the FileWriter constructor:

new FileWriter("output.txt", true)

Full Example

Output
Click Run to execute your code