Java Files newBufferedWriter()

In this guide, you will learn about the Files newBufferedWriter() method in Java programming and how to use it with an example.

1. Files newBufferedWriter() Method Overview


The Files.newBufferedWriter() method opens a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.


static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options)


- path: The path to the file to open or create.

- cs: The charset to use for encoding. If not specified, the default charset, which is Charset.defaultCharset(), is used.

- options: Options specifying how the file is opened. If no options are present, the file is created, truncated, or opened for writing.

Key Points:

- This method is intended for writing text files in a simple and efficient manner.

- The BufferedWriter ensures the file is properly closed after all bytes have been written or when an I/O error, or other runtime error, is detected.

- The method writes to the file directly without any buffering, making it suitable for writing to large files.

2. Files newBufferedWriter() Method Example

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesBufferedWriterExample {
    public static void main(String[] args) {
        Path path = Paths.get("output.txt");

        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
            writer.write("Hello, World!");
            writer.write("This is a sample text.");
        } catch (IOException e) {
            System.out.println("Failed to write to the file: " + e.getMessage());


The file output.txt will contain:
Hello, World!
This is a sample text.


In this example, the Files.newBufferedWriter() method is used to create a BufferedWriter for the file output.txt. The StandardCharsets.UTF_8 charset is used for encoding. 

The StandardOpenOption.CREATE option ensures that the file is created if it does not exist or opened if it does exist. Text is then written to the file using the write() method of the BufferedWriter and a new line is added using the newLine() method.