Reading lines with BufferedReader and checking for end of file
Asked Answered
E

8

18

If I have something like this in my code:

String line = r.readLine();  //Where r is a bufferedReader

How can I avoid a crash if the next line is the end of the file? (i.e. null)

I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.

If there is something there then all is OK, but I can't be guaranteed that there will be something there.

So if I do something like: (pseudo code):

if (r.readLine is null)
//End code

else {check line again and excecute code depending on what the next line is}

The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?

I've not worked out a way to do this - any suggestions would be a great help.

Ermines answered 16/7, 2013 at 14:10 Comment(1)
Really wish people would leave a reason when down-voting. A down-vote is supposed to indicate there is something wrong with a question so maybe it can be reformatted. Down-voting without leaving a reason as to why the downvote has been cast helps no-oneErmines
B
48

Am... You can simply use such a construction:

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}
Brightness answered 16/7, 2013 at 14:14 Comment(1)
As you answered first, I'll delete mine:)Capreolate
K
8

If you want loop through all lines use that:

while((line=br.readLine())!=null){
    System.out.println(line);
}
br.close();
Kneehole answered 16/7, 2013 at 14:15 Comment(0)
A
6

You can use the following to check for the end of file.

public bool isEOF(BufferedReader br)  
{
     boolean result;

     try 
     {
         result = br.ready();
     } 
     catch (IOException e)
     {
         System.err.println(e);
     }
     return result;
}
Accolade answered 23/6, 2017 at 20:46 Comment(2)
This is better than assigning + comparing in the while clause, in my opinion.Made
This fails silently on exception and BufferedReader::ready can return false even if the next read will succeed.Laconic
G
2

In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.

String line = r.readLine();
while(line!=null){
   System.out.println(line);
   line = r.readLine();
}
Gravimeter answered 21/6, 2018 at 11:7 Comment(1)
Keeping the assignment out of the while clause keeps it much cleaner.Chromatology
K
1

A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class LineOperation {
    public static void main(String[] args) throws IOException {
            Files.newBufferedReader(Paths.get("C://xyz.txt")).
            lines().
            collect(Collectors.toSet()). // You can also use list or any other Collection
            forEach(System.out::println);
    }

}
Knowledgeable answered 23/7, 2018 at 7:48 Comment(1)
There is no reason to collect the lines. Remove the collect() call and do forEach() on the stream.Insomuch
R
1

You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.

A part from BufferReader you could use Java Scanner class to read the file and check the last line.

Buffer Reader

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line
    }
}

Scanner

   try {
     Scanner scanner = new Scanner(new FileReader(file));
         while (scanner.hasNext()) {
            // Above checks whether it has or not ....
            }
       } catch (IOException e) {
            e.printStackTrace();
       }

If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.

In addition, BufferReader is faster than Scanner.

Rosendorosene answered 10/2, 2020 at 6:21 Comment(0)
R
0

If you would like to do some check like:

if (reader.ready())
       stringBuilder.append("#");

You can use ready()

public static void check() throws IOException {
        InputStream in = new FileInputStream(new File(filePath));
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            if (reader.ready())
                stringBuilder.append("#");
        }
        String returnedString = stringBuilder.toString();
        System.out.println(returnedString);
    }
Right answered 28/4, 2022 at 15:48 Comment(0)
D
-4

You could purposely have it throw the error inside your loop. i.e.:

String s = "";
while (true) {
    try {
        s = r.readline();
    }catch(NullPointerException e) {
        r.close();
        break;
    }
    //Do stuff with line
}

what everyone else has sad should also work.

Dottydoty answered 16/7, 2013 at 14:20 Comment(1)
Would this actually throw NullPointerException? I think you need to check if (s == null).Oenone

© 2022 - 2025 — McMap. All rights reserved.