我正在尝试制作一个Java程序,该程序对'* .txt'-文件中的单词和行进行计数。到目前为止,一切都很好。该代码仅在“ .txt”只有两行时有效。如果在其中添加更多行,我在代码的。split(“”);)部分会收到NullPointerException。我读过某处可能带有。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("\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输出:大声笑我很傻哈哈伊德克传送一半
分割的字符串:一世上午漂亮笨。哈哈idk线程异常“主要” java.lang.NullPointerException在txt_counter.main(txt_counter.java:32)
在while循环中,您从缓冲的读取器中读取一行,并将其与null进行比较,但是从不使用该行。然后,在while循环的主体中,读取下一行而不检查结果是否为空。逐行读取文件的通常方法是这样的:
String line;
while ((line = binput.readLine()) != null) {
String[] woerter = line.replaceAll("\\s+", " ").split(" ");
...