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.

Zippy
  • 3,826
  • 5
  • 43
  • 96
  • 4
    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-one – Zippy Feb 25 '15 at 14:02

8 Answers8

47

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

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
8

If you want loop through all lines use that:

while((line=br.readLine())!=null){
    System.out.println(line);
}
br.close();
Lugaru
  • 1,430
  • 3
  • 25
  • 38
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;
}
slfan
  • 8,950
  • 115
  • 65
  • 78
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();
}
Sushant Somani
  • 1,450
  • 3
  • 13
  • 31
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);
    }

}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Abhinav
  • 530
  • 8
  • 21
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.

Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
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);
    }
-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.

sparks
  • 736
  • 1
  • 9
  • 29