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

如何实现接收File参数的文件读取方法并返回char数组?

问题解决:读取File并返回char数组

原代码的问题

  • aux初始化为null,执行st+=aux时会将null转为字符串"null"拼接,完全没有实现内容收集逻辑,最终返回的还是null
  • 未关闭BufferedReader,存在资源泄漏风险
  • readLine()会丢弃每行末尾的换行符,若需要保留文件原有格式,当前逻辑无法实现
  • 循环逻辑错误,每次读取的内容未被累积存储

修正后的实现方案

方案一:使用StringBuilder累积内容(兼容JDK 8+)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String[] args) throws IOException {
        File f = new File("word.txt");
        char[] word = readWordFile(f);
        System.out.println(word);
    }

    // 读取文件内容并返回char数组
    public static char[] readWordFile(File f) throws IOException {
        // try-with-resources语法自动关闭资源
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            StringBuilder sb = new StringBuilder();
            String st;
            // 读取每行并添加换行符保留原格式
            while ((st = br.readLine()) != null) {
                sb.append(st);
                sb.append(System.lineSeparator());
            }
            return sb.toString().toCharArray();
        }
    }
}

方案二:使用NIO的Files类(更简洁,JDK 7+)

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class ReadFile {

    public static void main(String[] args) throws IOException {
        File f = new File("word.txt");
        char[] word = readWordFile(f);
        System.out.println(word);
    }

    public static char[] readWordFile(File f) throws IOException {
        // 直接读取文件所有内容转成字符串,再转为char数组
        String content = Files.readString(f.toPath(), StandardCharsets.UTF_8);
        return content.toCharArray();
    }
}

说明

  • 方案一的try-with-resources语法会自动关闭流资源,避免泄漏
  • 若不需要保留原文件的换行符,可删除方案一中的sb.append(System.lineSeparator());
  • 方案二依赖Java NIO API,代码更简洁,适合JDK 7及以上版本使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:39:57