Search code examples
javanullbufferedreader

How can I suppress the null output of a BufferReader?


Using the following code to split the output of a reader into strings which are then used in a constructor. However when the bufferreader reaches the end of the stream it outputs null, which then causes a null pointer exception in the constructor.

List<Pattern> resultList = new LinkedList<Pattern>();
    BufferedReader buff = new BufferedReader(r);
    String current;
    while (buff != null) {
        current = buff.readLine();
        System.out.println(current);
        Pattern p = new Pattern(current);
        resultList.add(p);

        }
    return resultList;

I've tried putting an if statement to test if the current string is null, however I don't know what to put in the body of the if-clause. Any help would be greatly appreciated


Solution

  • buff is never going to be null - it's the return value of readLine which is null when you reach the end of the data. That's what you need to check, typically with code which assigns the value to a variable and checks it in one go:

    String current;
    while ((current = buff.readLine()) != null) {
        System.out.println(current);
        Pattern p = new Pattern(current);
        resultList.add(p);
    }