【问题标题】:NullPointerException and BufferedReaderNullPointerException 和 BufferedReader
【发布时间】:2015-05-16 03:19:41
【问题描述】:

我的程序不断向我抛出 nullPointerException,我不知道为什么。我想也许是因为 bufferedReader 但我不确定。

String line = reader.readLine();
while (!line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
    line = reader.readLine();
}

是的,它被包裹在 try - catch 块中。它说问题出在while-line上。它不适用于“if (line != null)”。我真的不知道是什么原因造成的。感谢您的帮助。

【问题讨论】:

  • 发布足够的代码,以便有人可以重现该问题。
  • 您需要使用调试器,并逐行执行您的代码。这样你就会发现你的问题,而且你可能会学到很多东西

标签: java nullpointerexception bufferedreader readline


【解决方案1】:

问题似乎与您的以下代码行有关:

String line = reader.readLine();
while (!line.isEmpty()) {   

}

如果文件中没有可读取的内容,则行将为空。因此while循环中的异常。您正在尝试在空引用上调用方法。

话虽如此,从文件中读取行的传统方法是将读取的行分配给 while 条件本身中的变量(代码未测试):

String line = "";
while ((line=reader.readLine()!=null) && !line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
}

【讨论】:

  • 感谢大家的帮助,我确实调试了它,最后几乎完全重写了它以避免可能的空值。
  • 我解开了一切并重写了一切。我认为在这种情况下没有任何帮助。
【解决方案2】:

我遇到了同样的错误,这意味着套接字在尝试在服务器上读取时正在关闭另一个连接的客户端。

为了添加一些上下文,我正在运行一个服务器,并且各种客户端通过 java 套接字连接到它。当客户端关闭套接字时,我在服务器端遇到此错误。

所以为了解决这个问题,我决定在每次连接后都关闭服务器端和客户端套接字。我这样做的方式是在客户端关闭之前,它会在关闭其套接字之前向服务器发送一条“退出”消息。当服务器读取“退出”消息时,它也会关闭其套接字。

例如:

  • 客户端
if(Quit){
   if(mySocket != null && !mySocket.isClosed()) {
        output.println("quit");
        output.flush();
        
        try {
            mySocket.close();
        } catch (IOException e) {
            System.out.println("Close net variables exception - " + e.getMessage());
        }
    }
}
  • 服务器端
String line = input.readLine(); //Thread stops here untill it reads something

if(line.equals("something")){
   do_something();
else if(line.equals("quit")){
   try {
        mySocket.close();
    } catch (IOException e) {
        System.out.println("Close net variables exception - " + e.getMessage());
    }
else{
   do_default();
}

为我工作,希望对您有所帮助!

【讨论】:

  • 你能发布你对此做了什么吗?
  • 当然!尽我所能更新,希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多