问题
Spring Boot 打成 jar 包运行,要获取 resources 中的资源文件,使用基于文件路径来获取文件会报异常的。
如下方式都会报异常:
ClassPathResource classPathResource = new ClassPathResource("template.xlsx");
File file = classPathResource.getFile();
// 或
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template.xlsx");
异常:
class path resource [template.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/xxx/xxx/pre-manager/manager-provider/target/manager-provider.jar!/BOOT-INF/classes!/template.xlsx
原因:是该文件路径是基于操作系统的访问路径,而打包到 jar 中的文件的路径已无法被操作系统识别了。
解决
使用基于流的方式创临时文件来获取,如下:
ClassPathResource classPathResource = new ClassPathResource(SysConstants.DISEASE_IMPORT_TEMPLATE_PATH);
// 是文件
File file = File.createTempFile("template", ".xlsx");
FileUtils.copyInputStreamToFile(classPathResource.getInputStream(), file);
// 是字符串
byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
String str = new String(bytes, StandardCharsets.UTF_8);
参考
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载