# Use Files.newBufferedReader

# Properties

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

# Description

Java 7 introduced the Files class that contains convenience methods for operating on files. This rule makes use of the Files.newBufferedReader method for initializing BufferedReader 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.

# 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);

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊