打包成jar后读取文件的大坑:使用ClassPathResource获取classpath下文件失败

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

private static List<Integer> test(String filePath) {
    try {
        ClassPathResource classpathResource = new ClassPathResource(filePath);
        File file = classpathResource.getFile();
        List<Integer> readLines = Files.readLines(file, Charsets.UTF_8, new LineProcessor<List<Integer>>() {
            List<Integer> sorts = new ArrayList<>();
            @Override
            public List<Integer> getResult() {
                return sorts;
            }
            
            @Override
            public boolean processLine(String s) throws IOException {
                sorts.add(Integer.parseInt(s));
                return true;
            }
        });
        return readLines;
    } catch (Exception e) {
        logger.error("load sort file error...",e);
        throw new RuntimeException(e);
    }
}

public static void main(String... s) {
    String fp = "data/test.txt";
    List<Integer> list = test(fp);
}

通过mvn打成jar包:

  <build>
    <plugins>
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
     </plugins>
  </build>

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

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
        at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:53) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE]
        at hello.whz.Application.lambda$lookup$0(Application.java:30) [classes!/:1.0-SNAPSHOT]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.8.RELEASE.jar!/:1.5.8.RELEASE]
        ... 14 common frames omitted

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

原因分析:

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

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

而getFile方法如下:

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

修改后的代码:

ClassPathResource classpathResource = new ClassPathResource(filePath);
try (
    InputStream is = classpathResource.getInputStream(); //使用流来处理
    BufferedReader bf = new BufferedReader(new InputStreamReader(is));
) {
    String str;
    while ((str = bf.readLine()) != null) {
        //按行处理
    }
    
} catch (Exception e) {

} 

 参考:

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

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

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值