Search code examples
javabufferedreader

Java NullPointerException in reading


I have problem with reading from my socket i read only if value isn't null but it doesnt't works.

@Override
public void run() {
    System.out.println("Reading from socket");
    while(true){
        try {
            if(!(br.readLine().equals(null)))read += br.readLine();
        } catch (IOException e) {
            System.out.println("error " + e);
        }
    }
}

here is error:

Exception in thread "Thread-4" java.lang.NullPointerException at connection.CreateConnection.run(CreateConnection.java:61) at java.lang.Thread.run(Unknown Source)


Solution

  • If br.readLine() returns null, then calling .equals(null) on it will throw an exception - it won't return true. You just want to compare reference identity with null.

    Calling .equals(null) is never useful, unless you're testing that your equals implementation works properly :)

    Additionally, you'll be skipping every other line by calling readLine() twice on each loop iteration.

    You want something like:

    String line;
    if ((line = br.readLine()) != null) {
        read += line;
    }
    

    ... except that will be painfully slow due to repeated string concatenation. You should almost certainly be using a StringBuilder instead.

    Also, doing all of this in a loop which catches IOException seems like a recipe for disaster - if the a call fails, it's very likely that it'll keep failing forever, whereupon your program is basically hung in a tight loop. You should almost certainly stop when you get an exception, rather than keeping going. For example:

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            read += line; // Or builder.append(line);
        }
    } catch (IOException e) {
        // Whatever you want to do
    }
    

    Finally, consider the value of whitespace, both horizontal and vertical, as well as the benefits of using braces even in single-statement if statements etc. The line if(!(br.readLine().equals(null)))read += br.readLine(); is compact at the expense of readability.