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

如何使用SpringBoot读取txt文件并将内容存入String数组

SpringBoot读取TXT文件提取单词存入String数组实现方案

核心思路

  • 借助SpringBoot内置的ResourceLoader加载文件资源,无需额外引入第三方依赖,同时兼容项目classpath内文件、服务器本地磁盘文件两种场景
  • 统一按指定编码读取文件文本内容,按自定义分隔规则拆分单词
  • 过滤空值、无效字符后转换为String数组返回

完整实现代码

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class WordFileReadService {

    private final ResourceLoader resourceLoader;

    // 构造注入Spring自带的资源加载器,无需额外配置
    public WordFileReadService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 读取TXT文件提取单词数组
     * @param fileTargetPath 资源路径,classpath:开头读项目resources下文件,file:开头读本地磁盘绝对路径
     * @return 拆分后的单词String数组
     */
    public String[] loadWordArrayFromTxt(String fileTargetPath) {
        try {
            Resource fileResource = resourceLoader.getResource(fileTargetPath);
            // 大文件建议用逐行读取方式,避免内存占用过高
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(fileResource.getInputStream(), StandardCharsets.UTF_8)
            );
            String fullContent = reader.lines().collect(Collectors.joining(" "));
            reader.close();

            // 按一个或多个空白字符(空格、换行、制表符)拆分,过滤空字符串
            return Arrays.stream(fullContent.split("\\s+"))
                    .filter(Objects::nonNull)
                    .map(String::trim)
                    .filter(word -> !word.isEmpty())
                    // 若需要自动去除单词首尾的标点(逗号、句号、引号等),放开下面这行注释
                    // .map(word -> word.replaceAll("^[\\pP]|[\\pP]$", ""))
                    .toArray(String[]::new);

        } catch (Exception e) {
            throw new RuntimeException("TXT文件读取处理失败:" + e.getMessage(), e);
        }
    }
}

调用方式

直接在需要用的地方注入Service调用即可,示例:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;

@RestController
public class TestController {

    private final WordFileReadService wordFileReadService;

    public TestController(WordFileReadService wordFileReadService) {
        this.wordFileReadService = wordFileReadService;
    }

    @GetMapping("/test-read")
    public String testRead() {
        // 例1:读取resources目录下的vocab.txt文件
        String[] words = wordFileReadService.loadWordArrayFromTxt("classpath:vocab.txt");
        // 例2:读取D盘下的vocab.txt本地文件
        // String[] words = wordFileReadService.loadWordArrayFromTxt("file:D:/vocab.txt");
        return "读取到单词共" + words.length + "个,内容:" + Arrays.toString(words);
    }
}

适配调整说明

  • 编码适配:如果TXT文件是GBK等其他编码,把代码里的StandardCharsets.UTF_8替换为Charset.forName("GBK")即可
  • 分隔符适配:如果文件里的单词不是用空白分隔,而是用逗号、顿号等符号,把split("\\s+")的正则参数换成对应分隔规则即可,比如逗号分隔就写split(",")
  • 小文件简化:如果文件体积在10MB以内,可以把逐行读取的逻辑替换为StreamUtils直接读全量文本,代码更简洁:
    String fullContent = StreamUtils.copyToString(fileResource.getInputStream(), StandardCharsets.UTF_8);
    
  • 大文件适配:如果是GB级大文件,不要拼接全量文本,逐行读取时同步拆分单词存入集合,最后转数组即可,避免内存溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:54:22