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

Java中使用BufferedReader已判断非空仍抛空指针异常如何解决?

异常成因
  • 核心问题是BufferedReader.readLine()方法的调用逻辑错误:该方法每调用一次就会读取文件的下一行内容,读到文件末尾时返回null,你的代码中对同一个文件流重复调用该方法但未存储读取结果,导致提前读到文件末尾拿到null值:
    1. while循环判断条件bufferforFile2.readLine() != null已经读取了一行内容且未存储直接丢弃
    2. if判断bufferforFile2.readLine()!=null又读取了第二行内容,同样未存储直接丢弃
    3. 赋值给line2时第三次调用bufferforFile2.readLine(),此时如果文件剩余行数不足,就会拿到null,后续调用line2.split(",")时直接触发空指针异常。你看到的非空打印只能证明if判断那一次读取返回了非空,无法证明第三次读取的结果非空。
  • 潜在空指针风险:读取基准文件originalFile时,跳过表头后直接读取行赋值给line1,如果基准文件只有表头没有数据行,line1会为null,调用line1.split(",")也会触发空指针。
解决方法

每次调用readLine()后先把结果存储到临时变量中,只对临时变量做非空判断和后续处理,不要重复调用readLine()读取同一行。修正后的代码如下:

public static boolean IsValidFile(String fileEntry, String originalFile) {
    boolean output = true;
    // 声明临时变量存储读取到的行,避免重复调用readLine
    String line1 = null, line2 = null;
    try (
        // 用try-with-resources自动关闭流,避免资源泄漏
        BufferedReader bufferforFile1 = new BufferedReader(new FileReader(originalFile));
        BufferedReader bufferforFile2 = new BufferedReader(new FileReader(fileEntry))
    ) {
        // 跳过表头
        bufferforFile1.readLine();
        line1 = bufferforFile1.readLine();
        // 先判断基准文件非空再处理
        if (line1 == null) {
            System.out.println("基准文件无有效数据行");
            output = false;
            return output;
        }
        String firstDate = line1.split(",")[0];
        // 跳过待校验文件表头
        bufferforFile2.readLine();
        // 每次读取结果存到line2变量,判断变量非空再处理
        while ((line2 = bufferforFile2.readLine()) != null) {
            System.out.println("Value is not Null!");
            boolean condition = line2.split(",")[0].equals(firstDate);
            System.out.println("Boolean condition is "+condition);
            if (!condition) {
                System.out.println("Date mismatch: file closed.");
                output = false;
                return output;
            }
        }
        return output;
    } catch (IOException e) {
        e.printStackTrace();
        return output;
    }
}

修正后的代码额外用了try-with-resources语法自动关闭文件流,解决了原代码未手动关闭流导致的资源泄漏问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:45:05