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

本地正常、EC2运行Jar时加载文件触发NoSuchFileException的解决咨询

解决Jar包中读取Classpath资源的NoSuchFileException问题
  • 问题根源:Jar包内的资源并非文件系统中的独立文件,而是Jar归档里的条目。Paths.get()只能识别真实的文件系统路径,无法解析Jar包内部的资源路径,所以打包运行时会抛出NoSuchFileException。

  • 修复代码:放弃通过路径读取,直接用ClassPathResource的输入流获取内容:

import org.springframework.core.io.ClassPathResource;
import java.nio.charset.StandardCharsets;

// 正确读取Jar内的temp.md文件
String mdContent = new String(
    new ClassPathResource("temp.md").getInputStream().readAllBytes(),
    StandardCharsets.UTF_8
);
  • 注意事项:
    • 确保temp.md在打包后确实存在于Jar包的根目录(对应src/main/resources下的文件,打包后会放在Jar的根路径)。
    • 如果非Spring环境,也可以用ClassLoader.getResourceAsStream()实现相同逻辑:
      String mdContent = new String(
          Thread.currentThread().getContextClassLoader()
              .getResourceAsStream("temp.md").readAllBytes(),
          StandardCharsets.UTF_8
      );
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:50:21