# Use Files.newBufferedReader

# Description

Java 7 introduced the Files (opens new window) class that contains convenience methods for operating on files. This rule makes use of the Files.newBufferedReader (opens new window) method for initializing BufferedReader (opens new window) objects to read text files in an efficient non-blocking manner.

# Benefits

Achieve better performance by using non-blocking I/O operations offered by the java.nio package.

# Tags

# Code Changes

# Creating the BufferedReader from a new FileReader

Pre

String location = "path/to/file";
BufferedReader br = new BufferedReader(new FileReader(location));

Post

String location = "path/to/file";
BufferedReader br = Files.newBufferedReader(Paths.get(location), Charset.defaultCharset());

# Creating the FileReader from a new File

Pre

String location = "path/to/file";
BufferedReader br = new BufferedReader(new FileReader(new File(location)));

Post

String location = "path/to/file";
BufferedReader br = Files.newBufferedReader(Paths.get(location), Charset.defaultCharset());

# Declaring the Resources on a Try-With-Resource Statement

Pre

try (FileReader reader = new FileReader(new File("path/to/file"));
		BufferedReader br = new BufferedReader(reader)) {
    //...
} catch (IOException e) {}

Post

try (BufferedReader br = Files.newBufferedReader(Paths.get("path/to/file"), Charset.defaultCharset())) {
    //...
} catch (IOException e) {}

# Providing the Charset Manually (Since Java 11)

Pre

String location = "path/to/file";
BufferedReader br = new BufferedReader(new FileReader(location, StandardCharsets.UTF_8));

Post

String location = "path/to/file";
BufferedReader br = Files.newBufferedReader(Paths.get(location), StandardCharsets.UTF_8);

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID UseFilesBufferedReader
First seen in jSparrow version 3.21.0
Minimum Java version 7
Remediation cost 5 min
Links