解决本地springboot项目可以正常访问Resource下的文件,打成jar包不能访问

当我把boot项目打成jar包放在服务器的时候出现如下问题:class path resource [xxxx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxxx.jar!/BOOT-INF/classes!xxxx。

解决代码如下:

 

private static final String FILE_PATH_PATH = "/static/文件目录/";


// 获取文件绝对路径
public static String getFileAbsolutePath(String fileName) throws IOException {
Resource resource = new ClassPathResource(FILE_PATH_PATH + fileName);

// 确认资源存在
if (!resource.exists()) {
throw new FileNotFoundException("找不到文件: " + fileName);
}

// 创建临时文件
File tempFile = File.createTempFile("temp", null);
tempFile.deleteOnExit(); // 确保程序结束时删除临时文件

// 将资源复制到临时文件
Files.copy(resource.getInputStream(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

// 返回临时文件的绝对路径
return tempFile.getAbsolutePath();
}

然后,其他业务层只需要输入文件名就能正常使用了,本地或者服务器都能正常访问

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值