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

Java文件读取方法返回null求助:如何返回预期字符串?

问题解决:读取文件方法返回null的修复方案

问题根源

你当前的代码逻辑是每次用新读取的行覆盖fileContents变量,当循环结束时,readLine()返回null(表示文件已读完),因此fileContents最终是null,自然返回null。要返回完整文件内容,需要把所有读取到的行累加起来,而不是覆盖。

修复后的代码

public static String readTestResults(String fileName) {
    // 使用StringBuilder高效累加多行内容,避免String拼接的性能损耗
    StringBuilder contentBuilder = new StringBuilder();

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        // 逐行读取,直到文件末尾(readLine()返回null)
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            contentBuilder.append(line);
            // 追加系统默认换行符,保留原文件的行结构,可根据需求替换或移除
            contentBuilder.append(System.lineSeparator());
        }
        System.out.println("test: " + contentBuilder.toString());
        // 可选:trim()移除最后多余的换行符,若不需要可直接返回toString()
        return contentBuilder.toString().trim();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Print if code reaches here");
    return contentBuilder.toString();
}

关键改动说明

  • 替换存储方式:用StringBuilder替代单一String变量,实现内容累加而非覆盖,同时避免多次String拼接的性能浪费。
  • 自动资源管理:使用try-with-resources语法(Java 7及以上支持),无需手动调用reader.close(),自动关闭IO资源,防止资源泄漏。
  • 循环逻辑优化:直接在循环条件中完成行读取和赋值,代码更简洁清晰。
  • 返回完整内容:最终返回StringBuilder转换的字符串,包含所有读取到的行内容,不会出现null(即使文件为空,也会返回空字符串)。

可选调整

如果不需要保留原文件的换行结构,可以移除contentBuilder.append(System.lineSeparator()),或者替换为其他分隔符(比如, )来拼接内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:04:55