I want my program to do something when it finds the end of a file (EOF) at the end of the last line of text, and something else when the EOF is at the empty line AFTER that last line of text. Unfortunately, BufferedReader seems to consider both cases equal.
For example, this is my code to read the lines to the end of the file:
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
if (line.equals("")) {
System.out.println("Found an empty line at end of file.");
}
}
If file.txt contained this, it wouldn't print:
line of text 1
another line 2//cursor
This wouldn't print either:
line of text 1
another line 2
//cursor
However, this will:
line of text 1
another line 2
//cursor
What reader can I use to differentiate the first two cases?
You can use BufferedReader.read(char[] cbuf, int off, int len)
method. When end of file is reached, return value -1
, you can check if the last buffer read ended with a line separator.
Admittedly, the code would be more complicated as it will have to manage the construction of lines from the read char[]
buffers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With