ClassPathResource报错cannot be resolved to absolute file path

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

post

Vitah Lin

1 min read
0

/

问题描述

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

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

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

解决方案

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

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

参考链接

Don't miss these

0
socket基本介绍

Vitah Lin

·8 min read

0
socket的阻塞模式和非阻塞模式

Vitah Lin

·5 min read

0
getaddrinfo函数详解及使用举例

Vitah Lin

·6 min read

0
Linux errno详解

Vitah Lin

·1 min read

0
struct声明中的__attribute__ ((packed))关键字

Vitah Lin

·1 min read

0
typedef详解

Vitah Lin

·1 min read