# How to write to a file using BufferedWriter in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 6, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-write-file-using-bufferedwriter

> A short article to learn how to write to a file using the BufferedWriter class 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:

```java
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:

```bash
Hey, there!
See you soon.
```

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

```java
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:

```java
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:

```java
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](https://attacomsian.com/blog/java-read-write-files-nio-api) guide for more examples. 

## Further Reading

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

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
