Java Files newBufferedReader()

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

1. Files newBufferedReader() Method Overview

Definition:

The Files.newBufferedReader() method opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.

Syntax:

static BufferedReader newBufferedReader(Path path, Charset cs)

Parameters:

- path: the path to the file to open.

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

Key Points:

- The reader will read sequences of characters in line format. It's useful for reading lines from a file.

- This method ensures the file is properly closed when all bytes have been read or when an I/O error, or other runtime error, is detected.

- The method reads the file directly without any buffering, making it suitable for reading large files.

2. Files newBufferedReader() Method Example


import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

        try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Failed to read the file: " + e.getMessage());
        }
    }
}

Output:

[Contents of the sample.txt file would be printed line by line]

Explanation:

In this example, the Files.newBufferedReader() method is used to create a BufferedReader for the file sample.txt. The StandardCharsets.UTF_8 charset is used for decoding. The file's contents are then read line by line using the readLine() method of the BufferedReader and printed to the console.

Comments