# 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);
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | UseFilesBufferedReader |
First seen in jSparrow version | 3.21.0 |
Minimum Java version | 7 |
Remediation cost | 5 min |
Links |