SpringBoot2实践系列(五十六):获取jar包resources中的资源文件

star2017 1年前 ⋅ 320 阅读

问题

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);

参考

  1. Classpath resource not found when running as jar
  2. 无法获取 Spring Boot jar 包 resources 中的文件
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: