How to write to a file using BufferedWriter in Java

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.