Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader readLine() issue: detecting end of file and empty return lines

Tags:

java

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?

like image 793
MLQ Avatar asked Mar 29 '12 09:03

MLQ


1 Answers

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.

like image 98
hmjd Avatar answered Oct 29 '22 18:10

hmjd