Spring Boot中JAR包内资源需用ClassLoader.getResourceAsStream()或ClassPathResource获取InputStream,不可用FileInputStream;资源须置于src/main/resources下,路径为classpath相对路径,且需判空处理。

在 Spring Boot 打包成 JAR 后,FileInputStream 无法直接读取 JAR 包内的资源文件,因为这些文件不再以普通文件形式存在于文件系统中,而是作为归档条目嵌在 JAR 内。此时用 new FileInputStream("xxx.txt") 会抛出 FileNotFoundException。
优先使用 ClassLoader 获取 InputStream
Spring Boot 推荐通过类加载器获取资源流,这是最可靠、跨环境兼容的方式:
- 用
getClass().getClassLoader().getResourceAsStream("xxx.txt"),路径为 classpath 根目录下的相对路径(如static/config.txt或application.properties) - 若资源在某个包下(如
com.example.config/data.json),路径写成"com/example/config/data.json",不加前导斜杠 - 返回值可能为
null,务必判空,避免NullPointerException
用 Spring 的 Resource 工具更简洁安全
Spring 提供了 Resource 抽象,自动适配 JAR 内/文件系统/网络等位置:
- 注入
ResourceLoader或直接用new ClassPathResource("xxx.txt") ClassPathResource resource = new ClassPathResource("templates/index.html");- 调用
resource.getInputStream()获取流,无需关心底层是否在 JAR 中 - 支持 Ant 风格路径(如
classpath*:mapper/*.xml),适合批量加载
注意路径写法和资源位置
资源必须放在 src/main/resources(或 src/main/resources/static、templates 等标准目录),编译后才会进入 classpath:
立即学习“Java免费学习笔记(深入)”;
- 错误示例:
new FileInputStream("src/main/resources/config.txt")—— 运行时该路径不存在 - 正确写法:
new ClassPathResource("config.txt").getInputStream() - 如果文件在
resources/conf/下,路径写"conf/app.yaml"
不要尝试解压 JAR 或转成 File
试图用 getResource().toURI().getPath() 转 File 在 JAR 环境下会失败(URI 是 jar:file://... 格式,不能直接构造 File):
- 会抛
IllegalArgumentException或返回 null - 即使临时解压,也增加复杂度、线程安全风险和性能开销
- 所有需求都可通过
InputStream或Resource满足,无需落地为 File
不复杂但容易忽略:只要资源在 classpath 里,就别碰 FileInputStream,用 Resource 或 ClassLoader.getResourceAsStream 就够了。


















