SpringBoot打成jar后无法读取根路径和文件


记录一下getContextClassLoader().getResource()之坑FileNotFoundException

今早部署代码到测试环境之后,测试需求的时候出现了FileNotFoundException,发现是获取字体路径的时候报错了,很奇怪,在本地调试的时候并未发现此问题。
错误日志:

    Caused by: java.io.FileNotFoundException: /opt/supplier_web/supplier_web.jar!/BOOT-INF/lib/supplier_web.web-0.0.1.jar!/font/simsun.ttf (No such file or directory)

1513877-20200316205433601-1703636410.png

问题代码如下:

1513877-20200316205511002-1846389755.png

排查发现问题如下:

这是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。

解决办法:

使用ClassPathResource解决问题。
1513877-20200316205528479-919509865.png

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot,可以使用`ResourceLoader`来加载目录下的文件。以下是一些常见的方法: 1. 通过`ResourceLoader`加载文件 ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.nio.file.Files; import java.nio.file.Paths; @Component public class MyComponent { private final ResourceLoader resourceLoader; public MyComponent(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @PostConstruct public void init() throws Exception { Resource resource = resourceLoader.getResource("classpath:myfile.txt"); byte[] contents = Files.readAllBytes(Paths.get(resource.getURI())); System.out.println(new String(contents)); } } ``` 2. 通过`ClassPathResource`加载文件 ```java import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.nio.file.Files; import java.nio.file.Paths; @Component public class MyComponent { @PostConstruct public void init() throws Exception { ClassPathResource resource = new ClassPathResource("myfile.txt"); byte[] contents = Files.readAllBytes(Paths.get(resource.getURI())); System.out.println(new String(contents)); } } ``` 以上代码,第一个例子是通过`ResourceLoader`加载文件,第二个例子是通过`ClassPathResource`加载文件。注意,文件路径的`classpath:`前缀表示文件在类路径下。如果文件不在类路径下,可以使用`file:`前缀来指定绝对路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值