阅读中的Java NullPointerException

g_1*_*1_k 0 java bufferedreader

我有问题从我的套接字读取我只读取如果值不为null但它不起作用.

@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是错误:

在java.lang.Thread.run(未知来源)的connection.CreateConnection.run(CreateConnection.java:61)中的线程"Thread-4"java.lang.NullPointerException中的异常

Jon*_*eet 8

如果br.readLine()返回null,则调用.equals(null)它将抛出异常 - 它不会返回true.您只想比较参考标识null.

通话.equals(null)从来没有用,除非你测试你的equals执行工作正常:)

此外,您将通过readLine()在每次循环迭代中调用两次来跳过所有其他行.

你想要的东西:

String line;
if ((line = br.readLine()) != null) {
    read += line;
}
Run Code Online (Sandbox Code Playgroud)

...除了由于重复的字符串连接而会非常缓慢.你几乎肯定会使用一个StringBuilder代替.

此外,在一个捕获的循环中完成所有这些IOException似乎是一个灾难的处方 - 如果一个调用失败,它可能会永远失败,于是你的程序基本上挂在一个紧密的循环中.当你得到异常时,你几乎肯定会停下来,而不是坚持下去.例如:

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

最后,考虑空白的值,包括水平和垂直,以及使用大括号的好处,即使在单语句if语句等中if(!(br.readLine().equals(null)))read += br.readLine();也是如此.该行是以可读性为代价的.