当我把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();
}
然后,其他业务层只需要输入文件名就能正常使用了,本地或者服务器都能正常访问