springboot打成jar包后linux服务器上无法读取resources资源文件里文件路径的问题

1、起因

将支付验正证书信息放在项目的resources资源文件下在本地通过

this.getClass().getResource("/").getPath()

可以正常读取证书信息,但是打包部署到linux服务器上时报java.io.FileNotFoundException

2、解决方法

使用applicationHome.getSource().getParentFile().toString();读取jar包中的文件流具体代码如下:

     public class CopyCertFile {

    /**
     * (解决linux系统上找不到证书文件问题)
     * @param certPath
     */
    public void copyCertFile(String certPath){
        ApplicationHome applicationHome = new ApplicationHome(CopyCertFile.class);
        //项目打包成jar包所在的根路径
        String rootPath = applicationHome.getSource().getParentFile().toString();
        String configFilePath = rootPath + certPath;
        File configFile = new File(configFilePath);
        if (!configFile.exists()) {
            try {
                //获取类路径下的指定文件流
                InputStream in = this.getClass().getClassLoader().getResourceAsStream(certPath);
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "证书文件找不到"), configFile);
            } catch (IOException e) {
                throw new IllegalArgumentException("保存文件证书失败->" + e.getMessage());
            }
        }
    }
}

                
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在使用Spring Boot时,可能会出现打成JAR运行后无法读取resources文件问题。这是因为在JAR包中,源文件会被打包到一个压缩文件中,而不是一个文件夹中。 解决这个问题有几种方法: 1. 使用Classloader获取源 可以使用Java的Classloader获取JAR包中的源。这种方法可行,但较繁琐。 举个例子: ```java ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("file.txt"); ``` 这样做可以读取位于JAR包中的file.txt文件。 2. 使用Spring提供的ResourceLoader Spring提供了ResourceLoader来处理此问题。我们可以注入ResourceLoader并使用它读取源。 举个例子: ```java @Autowired private ResourceLoader resourceLoader; public void readFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:file.txt"); InputStream inputStream = resource.getInputStream(); } ``` 这个方法还可以处理其他类型的源,例如网络源等。 3. 使用FileSystemResource 我们可以使用FileSystemResource读取文件。这种方法需要JAR包解压到文件夹中,然后使用FileSystemResource读取文件。 ```java Resource resource = new FileSystemResource(file.txt); InputStream inputStream = resource.getInputStream(); ``` 但是这种方法会使JAR包无法单独使用。 总之,以上三种方法都可以解决打成JAR运行后无法读取resources文件问题,我们可以根据实际情况选择其中一种方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

younha66

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

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

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

打赏作者

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

抵扣说明:

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

余额充值