当前位置:   article > 正文

打包成jar后读取文件的大坑:使用ClassPathResource获取classpath下文件失败_classpathresource 读取不到外部配置文件的信息

classpathresource 读取不到外部配置文件的信息

在springboot项目中,resource下创建data目录,然后把test.txt文件放进去,通过下面代码是可以读取其中内容的:

  1. private static List<Integer> test(String filePath) {
  2.     try {
  3.         ClassPathResource classpathResource = new ClassPathResource(filePath);
  4.         File file = classpathResource.getFile();
  5.         List<Integer> readLines = Files.readLines(file, Charsets.UTF_8, new LineProcessor<List<Integer>>() {
  6.             List<Integer> sorts = new ArrayList<>();
  7.             @Override
  8.             public List<Integer> getResult() {
  9.                 return sorts;
  10.             }
  11.             
  12.             @Override
  13.             public boolean processLine(String s) throws IOException {
  14.                 sorts.add(Integer.parseInt(s));
  15.                 return true;
  16.             }
  17.         });
  18.         return readLines;
  19.     } catch (Exception e) {
  20.         logger.error("load sort file error...",e);
  21.         throw new RuntimeException(e);
  22.     }
  23. }
  24.  
  25. public static void main(String... s) {
  26.     String fp = "data/test.txt";
  27.     List<Integer> list = test(fp);
  28. }


通过mvn打成jar包:

  1.   <build>
  2.     <plugins>
  3.          <plugin>
  4.              <groupId>org.springframework.boot</groupId>
  5.              <artifactId>spring-boot-maven-plugin</artifactId>
  6.          </plugin>
  7.      </plugins>
  8.   </build>


用命令行执行,会报如下错误:

  1. Caused by: java.io.FileNotFoundException: class path resource [application.yml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/sunmnet/JetBrains/workspace/bigdata-parse-table/target/bigdata-parse-table-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/application.yml
  2.         at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
  3.         at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:53) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
  4.         at hello.whz.Application.lambda$lookup$0(Application.java:30) [classes!/:1.0-SNAPSHOT]
  5.         at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.8.RELEASE.jar!/:1.5.8.RELEASE]
  6.         ... 14 common frames omitted


这是因为:在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流。(一定要用流,不要尝试去拿到绝对路径,否则报错!)

原因分析:

  1. Resource resource = new ClassPathResource("data/test/txt");
  2. String path = resource.getFile().getPath());


上述代码的getFile()方法,在本地可以运行成功,但是打包成jar后会报错。主要原因是在jar里,返回的是一个Jar协议地址:jar:file:/xxx/xx.jar!/xxxx

而getFile方法如下:

  1. public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
  2.     Assert.notNull(resourceUrl, "Resource URL must not be null");
  3.     if (!"file".equals(resourceUrl.getProtocol())) {
  4.         throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
  5.     } else {
  6.         try {
  7.             return new File(toURI(resourceUrl).getSchemeSpecificPart());
  8.         } catch (URISyntaxException var3) {
  9.             return new File(resourceUrl.getFile());
  10.         }
  11.     }
  12. }


 参考:

https://smarterco.de/java-load-file-from-classpath-in-spring-boot/

https://www.renfei.net/posts/1003293
 

原文地址:打包成jar后读取文件的大坑:使用ClassPathResource获取classpath下文件失败_赶路人儿的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/815928
推荐阅读
  

闽ICP备14008679号