跳到主要内容
开发与工程java, spring, troubleshootingSpring Boot 打包成 JAR 后,ClassPathResource 里的文件不在文件系统,不能用 getFile() 获取,应改用 getInputStream以流方式读取资源,避免 “cannot be resolved to absolute file path” 报错。

ClassPathResource报错cannot be resolved to absolute file path

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

ClassPathResource报错cannot be resolved to absolute file path

Vitah Lin

创建于 更新于 2 分钟阅读

问题描述

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

PLAIN
"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 对象创建和读取文件,导致无法获取到对应的文件对象

JAVA
ClassPathResource classPathResource = new ClassPathResource("static/satellite.txt");
File file = classPathResource.getFile();

解决方案

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

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

参考链接