如何修复我的.txt单词计数器中的NullPointerException



我正在尝试制作一个Java程序,该程序计算"*.txt"文件中的单词和行数。到目前为止还不错。只有当".txt"只有2行时,代码才能工作。如果放入更多行,我会在.split("(我的代码中的一部分。我读到一些地方可能有.readLine((-函数。但我真的不知道是什么导致了它。

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("nnsplitted 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
发送halp

分裂字符串:

很漂亮
愚蠢
haha
idk
线程中的异常
"main"java.lang.NullPointerException
在txt_counter.main(txt_countr.java:32(

在while循环中,您从缓冲读取器中读取一行,并将其与null进行比较,但该行永远不会被使用。在while循环的主体中,然后读取下一行,而不检查结果是否为null。逐行读取文件的常用方法如下:

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

最新更新