I have the following file lines.txt
Line1
Line2
Line3
I'm using a Scanner to parse the contents of this file line by line. I have the following setup in LinesReader.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Line {
Line(String content) {
this.content = content;
}
public String content;
public String toString() {
return content;
}
}
public class LinesReader {
public static Line buildLine(InputStream is) {
Scanner scanner = new Scanner(is);
if (scanner.hasNextLine()) {
return new Line(scanner.nextLine());
}
return null;
}
public static Line buildLine(Scanner scanner) {
if (scanner.hasNextLine()) {
return new Line(scanner.nextLine());
}
return null;
}
public static void main(String[] args) throws FileNotFoundException {
List<Line> lines = new ArrayList<>();
Line line = null;
FileInputStream is = new FileInputStream("lines.txt");
// buildLine(scanner) works as expected
while ((line = buildLine(is)) != null) {
lines.add(line);
}
System.err.println(lines);
}
}
The output is
[Line1]
The expected output would be
[Line1, Line2, Line3]
I understand the Scanner implements AutoCloseable, but according to the documentation that would only apply for a
try-with-resources construct and not here. Also, when i debug it is says the underlying stream is open. The second call to scanner.hasNextLine() unexpectedly fails.
If I construct the scanner once in main() it works as expected.
My java version is 1.8.0_275
In response to a comment by @Sweeper the scanner seems to buffer up more than what is consumed, the documentation sort of contradicts that.
for hasNextLine()
The scanner does not advance past any input.
for nextLine()
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Emphasis mine.