You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java TXT文件词数行数统计程序遇NullPointerException求解

解决你的Java文本统计程序空指针问题

嗨,我来帮你拆解下这个问题~你的NullPointerException根源其实很明确,就是重复调用readLine()方法导致的,咱们一步步理清楚:

问题到底出在哪?

看你循环里的这段核心代码:

while ( binput.readLine() != null ) {
 String[] woerter = binput.readLine().replaceAll("\\s+", " ").split(" ");
 // ... 其他逻辑
}

BufferedReader.readLine()每次调用都会读取文件的下一行,这就导致了一个致命问题:

  • 进入while条件判断时,你已经读取了一行内容(比如第1行),判断不为null后进入循环
  • 循环体里又调用一次readLine(),这时候读取的是下一行(比如第2行),处理这一行的单词
  • 下一轮while判断时,读取第3行,循环体里再读第4行……
  • 当文件行数是奇数,或者读到最后一行之后,循环体里的readLine()会返回null,这时候调用replaceAll()自然就抛出空指针异常了

修正方案:用变量保存读取的行

核心思路是:把每次读取的行保存到一个变量里,用这个变量完成非空判断和后续处理,避免重复调用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 = 0; // 修正初始值:空文件行数应为0,原1会导致错误计数
            int Wcount = 0;
            String line; // 用变量缓存每行内容
            // 读取一行到变量,同时判断是否为null
            while ((line = binput.readLine()) != null) { 
                Zcount++; // 每成功读取一行,行数+1
                // 处理空行:如果行仅含空白字符,跳过单词计数
                if (line.trim().isEmpty()) {
                    continue;
                }
                // 先trim去除首尾空白,再处理分割,避免空字符串单词
                String[] woerter = line.replaceAll("\\s+", " ").trim().split(" ");
                System.out.println("\n\nsplitted String: ");
                for (String word : woerter) {
                    System.out.println(word);
                }
                Wcount += woerter.length;
            }
            System.out.println("\nLines: " + Zcount);
            System.out.println("Words: " + Wcount);
        } finally {
            if (finput != null) {
                finput.close();
            }
            if (binput != null) {
                binput.close();
            }
        }
    }
}

几个关键优化点:

  • 避免重复读取:用line变量缓存每行内容,一次读取同时完成判断和后续处理,不会跳行或读到null
  • 修正行数计数逻辑:把Zcount初始值从1改成0,每读取一行就+1,空文件也能正确返回0行
  • 处理空行场景:如果某行只有空白字符,跳过单词计数,避免无效统计
  • 消除空字符串单词:在split前调用trim(),避免行首行尾的空格导致分割出空字符串

这样修改后,不管你的TXT文件有多少行,都能正确统计行数和单词数,再也不会出现空指针异常啦~

内容的提问来源于stack exchange,提问作者Destro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:47:56