Using Files.newBufferedReader with a try-with-resources block is the best practice for reading files in Java. Since BufferedReader implements AutoCloseable, the try-with-resources statement ensures that the file handle is automatically closed when the block is finished, even if an exception occurs.
Here is how you can implement it:
Basic Usage
This is the simplest way to read a file line-by-line using the default UTF-8 charset.
package org.kodejava.nio;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadFileExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
// The resource is declared inside the try parentheses
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle potential issues like a file not found or access errors
e.printStackTrace();
}
}
}
Key Highlights
- Automatic Cleanup: You don’t need a
finallyblock to callreader.close(). - Charset Support: If your file uses a specific encoding (like
ISO-8859-1), you can pass it as a second argument:try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.ISO_8859_1)) { ... } - Modern Alternative: Since you are using Java 25, if you want to read all lines into a stream for processing, you can use the
lines()method inside the block:try (BufferedReader reader = Files.newBufferedReader(path)) { reader.lines().forEach(System.out::println); }
Why use Files.newBufferedReader over new BufferedReader(new FileReader(...))?
- Path API: It works seamlessly with
java.nio.file.Path, which is more robust than the oldFileclass. - Explicit Charset: It defaults to UTF-8 (unlike older methods which might use the system’s default encoding), making your code more portable.
- Better Error Handling: It provides more descriptive
IOExceptionsubclasses (likeNoSuchFileException).
