【问题标题】:How do fix this NullPointerException in my .txt word-counter [duplicate]如何在我的 .text 单词计数器中修复此 NullPointerException [重复]
【发布时间】:2020-08-02 00:28:59
【问题描述】:

我正在尝试制作一个 Java 程序来计算 '*.txt' - 文件中的单词和行数。到目前为止,一切都很好。该代码仅在“.txt”只有 2 行时才有效。如果在其中添加更多行,我会在代码中的 .split(" "); 部分得到 NullPointerException。我在某处读过可能与 .readLine()-function 相关的内容。但我真的不知道是什么原因造成的。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class txt_counter {
static String FilePath = "C:\\Users\\diasc\\Desktop\\test.txt";

public static void main(String[] args) throws IOException{
    FileReader finput = null;
    BufferedReader binput = null;

    try {
        finput = new FileReader(FilePath);

        System.out.println("Orignal txt output:");
        int a;
        while ((a = finput.read()) != -1) {
            System.out.print((char) a);   
         }

         binput = new BufferedReader(new FileReader(FilePath));
         int Zcount = 1;
         int Wcount = 1;
         while ( binput.readLine() != null ) {
            String[] woerter = binput.readLine().replaceAll("\\s+", " ").split(" ");
            System.out.println("\n\nsplitted String: ");
            for(int i =0; i<woerter.length; i++)
            {
                System.out.println(woerter[i]);
            }
            Wcount = Wcount + woerter.length;
            Zcount++;
         }
         System.out.println("\nLines: " + Zcount);
         System.out.println("Words: " + Wcount);

    }finally {
         if (finput != null) {
             finput.close();
         }
         if(binput != null) {
             binput.close();
         }
    }
}

控制台输出:

原始 txt 输出:lol
我很愚蠢。哈哈 idk
发送暂停

拆分字符串:

上午
漂亮
愚蠢。
哈哈
idk
线程异常
“主” java.lang.NullPointerException
在 txt_counter.main(txt_counter.java:32)

【问题讨论】:

    标签: java nullpointerexception bufferedreader java-io


    【解决方案1】:

    在您的 while 循环中,您从缓冲读取器中读取一行并将其与 null 进行比较,但该行从未使用过。然后在 while 循环的主体中读取下一行而不检查结果是否为空。 通常逐行读取文件的方式是这样的:

    String line;
    while ((line = binput.readLine()) != null) {
      String[] woerter = line.replaceAll("\\s+", " ").split(" ");
      ... 
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2017-01-31
      相关资源
      最近更新 更多