# Use BufferedReader::lines
# Description
Java 8 introduced BufferedReader::lines
(opens new window) to generate a stream of elements representing lines in the BufferedReader
.
This rule, replaces While-Loops and For-Loops that are using BufferedReader::readLine
to iterate through lines of a file by a stream generated with BufferedReader::lines
.
# Benefits
Using streams instead of loops improves the readability and makes the code more compact.
# Tags
# Code Changes
# While Loops
Pre
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
String line;
while((line = bufferedReader.readLine()) != null) {
consume(line);
}
}
Post
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
bufferedReader.lines().forEach(line -> {
consume(line);
});
}
# For Loops with initializer
Pre
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
for(String line; (line = bufferedReader.readLine()) != null;) {
consume(line);
}
}
Post
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
bufferedReader.lines().forEach(line -> {
consume(line);
});
}
# For Loops without initializer
Pre
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
String line;
for(; (line = bufferedReader.readLine()) != null;) {
consume(line);
}
}
Post
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("file.name.txt"))) {
bufferedReader.lines().forEach(line -> {
consume(line);
});
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.
# Properties
Property | Value |
---|---|
Rule ID | BufferedReaderLines |
First seen in jSparrow version | 3.3.0 |
Minimum Java version | 8 |
Remediation cost | 5 min |