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

如何将jar包内的txt文件加载为字符串,解决打包后读取资源报错问题

Jar包内resources目录txt文件读取解决方案

核心问题说明

打包为jar后,resources下的文件不再是独立的磁盘文件,而是jar包内部的压缩条目,无法通过普通文件路径访问,必须通过类加载器读取资源流获取内容。你原有代码中还存在一个隐藏逻辑bug:读取到的文本内容存储在text变量中,但后续调用处理方法时传入的是文件路径字符串forestString,并未使用实际读取到的文本内容。


方案1:纯JDK原生实现(通过资源输入流读取,无第三方依赖)

String forestFilePath = this.forestkinFileMap.get(forestKin);
String fileContent = null;
// 资源路径无需以/开头,默认从classpath根目录(对应resources编译后路径)查找
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(forestFilePath)) {
    if (inputStream == null) {
        throw new IllegalArgumentException("未找到对应资源文件:" + forestFilePath);
    }
    // JDK11及以上可直接使用readAllBytes方法,低版本可替换为ByteArrayOutputStream流转字符串逻辑
    fileContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}
// 传入实际读取到的文件内容而非路径
UnitTile unit = this.unitTileFactory.processUnitCodeComposite(fileContent);
return unit;

方案2:Google Guava兼容写法

如果你希望继续使用Guava工具类,可调整为如下写法规避不同环境类加载器上下文差异问题:

String forestFilePath = this.forestkinFileMap.get(forestKin);
String fileContent = null;
try {
    URL resourceUrl = getClass().getClassLoader().getResource(forestFilePath);
    if (resourceUrl == null) {
        throw new IllegalArgumentException("未找到对应资源文件:" + forestFilePath);
    }
    fileContent = Resources.toString(resourceUrl, StandardCharsets.UTF_8);
} catch (IOException e) {
    e.printStackTrace();
}
UnitTile unit = this.unitTileFactory.processUnitCodeComposite(fileContent);
return unit;

注意事项

  • 资源路径不要添加前缀/,直接填写resources目录下的相对路径即可,例如resources下unit/forest_elf.txt直接传unit/forest_elf.txt
  • 打包后可手动解压jar包,确认目标txt文件存在于对应路径下,避免构建配置问题导致资源文件未被打入jar包

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:08