In this short article, you'll learn how to write to a text file using the BufferedWriter class in Java.

Using Files.newBufferedWriter() Method

In Java 8 or higher, you can use the new I/O API (NIO) Files.newBufferedWriter() static method to create a new instance of BufferedWriter. Here is an example:

try {
    // create a writer
    BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"));

    // write text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("See you soon.");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will create a new text file called output.txt with the following contents:

Hey, there!
See you soon.

If you want append data to a file only, do the following while creating BufferedWriter:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.APPEND);

Using BufferedWriter Class

For Java 7 or below, you can use the legacy File I/O API to write a text file as shown below:

try {
    // create a writer
    BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

    // write text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("See you soon.");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

Alternative: Files.write() Method

If you are using Java 8 or higher, use Files.write() instead of BufferedWriter. It is much cleaner and easier to use:

try {
    // data to write
    List<String> contents = Arrays.asList("Hey, there!", "How are you doing?");

    // write data
    Files.write(Paths.get("output.txt"), contents);

} catch (IOException ex) {
    ex.printStackTrace();
}

Check out how to read and write files using the Java NIO API guide for more examples.

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.