1

我是 Java 新手,我有很多关于文本的工作,并且我有一个想法来制作一个简单的程序来完成我的工作。我收到错误Exception in thread "main" java.lang.NullPointerException at com.text.work.Main.main(Main.java:25)

public class Main {

public static void main(String[] args) throws IOException {
    int someNumber = 0;
    PrintWriter saveFileOne = new PrintWriter("save.txt");
    PrintWriter saveFileTwo = new PrintWriter("otherThings.txt");
    FileReader fileReader = new FileReader("read.txt");
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String word = bufferedReader.readLine();


    do {
        word = bufferedReader.readLine();

        if (word.toString().equals("true")) { //this is line 25
            saveFileOne.println("No: " + ++someNumber + " = " + word);
        } else {
            saveFileTwo.println("Yes: " + someNumber + " = " + word);
        }

    } while (word != null);
    saveFileOne.close();
    saveFileTwo.close();
    bufferedReader.close();
    System.out.println("Done!");
}

}
4

4 回答 4

4

BufferedReader#readLine()文档:

返回: 包含行内容的字符串,不包括任何行终止字符,如果已到达流的末尾,则返回 null

这意味着您显然已经到达了流的末尾。

如果我是你,我会用一个来改变循环while

while ((word = buffer.readLine()) != null) {
 ..
}
于 2013-09-22T22:34:57.540 回答
4

显然wordnull因为 bufferedReader.readLine()遇到了流的结尾而返回了null

您应该null在进入 while 正文之前进行检查

while(null != (word = bufferedReader.readLine())) {
}

并在与常量进行比较时通常避免此类 NPE 调用equals这种方式:

"true".equals(other string) // "true" is never null
于 2013-09-22T22:35:18.903 回答
3

确保它word不为空。将代码更改为以下代码片段。

 do {
       word = bufferedReader.readLine();
       if(word != null) { //If word is null, no need to go in if block
         if (word.toString().equals("true")) {
            saveFileOne.println("No: " + ++someNumber + " = " + word);
         } else {
            saveFileTwo.println("Yes: " + someNumber + " = " + word);
         }
       }

    } while (word != null);

您还可以更改循环以读取文件,可以使用以下代码轻松完成

   if(buffer != null) {
        while ((word = buffer.readLine()) != null) {
           if (word.toString().equals("true")) {
               saveFileOne.println("No: " + ++someNumber + " = " + word);
           } else {
               saveFileTwo.println("Yes: " + someNumber + " = " + word);
           }
        }
    }
于 2013-09-22T22:31:07.870 回答
-1

我今天有同样的问题,两个额外的括号是答案

(word = bufferedReader.readLine()) != null)

于 2013-10-23T21:18:36.613 回答