Home > other >  BufferedReader in Java is skipping the last empty line in file
BufferedReader in Java is skipping the last empty line in file

Time:01-20

I have a file in following format:

Name: John
Text: Hello
--empty line-- Buffered Reader is reading this.
Name: Adam
Text: Hi
--empty line-- Buffered Reader is skipping this line.

I tried multiple ways to read the last empty line but its not working. Any suggestions? I have a program which validates that the message is in correct format or not. For the correct format there should be three lines first with name followed by text and empty line. As the last empty line is not read by the BufferedReader, my program always says that the message is in wrong format.

Sample Code I am using:

File file = new File(absolutePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
    process(line);
}

CodePudding user response:

The code is working the way it is supposed to. The last (empty) line is the end of file (EOF). A valid line is terminated by a carriage return and line feed. Line #3 is read because of this. I included an image of your file showing the text and symbols (used Notepad for this)

enter image description here

If I add another blank line at the end, notice how the previous blank line is now terminated.

enter image description here

I modified your code slightly to run this scenario

    public static void main (String[] args) throws IOException {
        File file = new File("emptyline.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        int linenum = 1;
        while ( (line = br.readLine()) != null) {
            System.out.println("Line "   (linenum  )   ": "   line);
        }
        br.close();
    }

When I run the code with two blank lines at the end, this is the result:

Line 1: Name: John
Line 2: Text: Hello
Line 3: 
Line 4: Name: Adam
Line 5: Text: Hi
Line 6: 

If you have software that validates this file based on data being structured this way, I am not sure what to say. That seems a bad way to validate a file. There are more effective ways to do this, like using checksum. Maybe if you try with two empty lines at the end, the validator will accept it as a correct format.

  •  Tags:  
  • Related