ClassPathResource报错cannot be resolved to absolute file path

Spring Boot 打包成 JAR 后,ClassPathResource 里的文件不在文件系统,不能用 getFile() 获取,应改用 getInputStream以流方式读取资源,避免 “cannot be resolved to absolute file path” 报错。

2 分钟293 字

ClassPathResource报错cannot be resolved to absolute file path开发与工程 · 2 分钟

#问题描述

需要读取一个本地的文件,将文件放到了 SpringBoot 项目的 resources 目录下,在使用 Idea 本地运行时,没有问题,但是发布为 JAR 包后,却报错无法找到文件,控制台打印错误如下:

plainplain折叠展开
"message": "class path resource [static/satellite.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/satellite/satellite/target/satellite-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/satellite.txt",

后来找到原因,在代码中使用 File 对象创建和读取文件,导致无法获取到对应的文件对象:

javajava折叠展开
ClassPathResource classPathResource = new ClassPathResource("static/satellite.txt");File file = classPathResource.getFile();

#解决方案

打包为 JAR 后,JAR 是一个压缩包,不能直接获取文件对象,要改为用流进行读取和创建,除非真的需要创建文件对象,否则即使获取到文件对象,可能后面也要转为用流进行下一步操作,只能用 ClassPathResource 对象的 getInputStream 方法,一步到位获取到:

JavaJava折叠展开
ClassPathResource classPathResource = new ClassPathResource("static/satellite.txt");// 打包成jar无法读取文件,要用流读取// File file = classPathResource.getFile();InputStream inputStream = classPathResource.getInputStream();

#参考链接

END · 2026.02.04
使用datagrip连接DynamoDB数据与中间件 · 1 分钟
上一篇 · 更早

使用datagrip连接DynamoDB

2026.02.04 · 1 分钟
你可能也想读
logback日志路径出现 IS_UNDEFINED 的问题2026.02.04 · 1 分钟↗编译Spring5.3.10源码2026.02.04 · 7 分钟↗Spring AOP源码之基本概念介绍2026.02.04 · 18 分钟↗
林
VitahLin

后端工程师 · 写长文
VitahLin 的个人博客,记录经济观察、股票研究,以及后端开发、分布式系统、数据库与 Redis 的原理和工程实践。