【发布时间】: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