AlexLipp
AlexLipp

Reputation: 149

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

Upvotes: 1

Views: 85

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500065

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);
}

Upvotes: 2

Steve P.
Steve P.

Reputation: 14699

Instead of putting an if into the while, change the conditions of your loop from:

while (buff != null)

to:

while ((current = buff.readLine()) != null)  

buff will not become null as a result of reaching the end of the stream, but current will become null when there is no more input to be returned

Upvotes: 1

Related Questions