cannot be resolved to absolute file path because it does not reside in the file system 错误

场景:

在Springboot中利用Resource来获取文件并在前端返回该文件, 本地测试正常, 打包到远程报错:流java.io.FileNotFoundException: class path resource [templates/startProcess.flt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/work/project/console.jar!/BOOT-INF/classes!/templates/xxx.flt

排查 jar包里文件地址是没问题的 

原因:

org.springframework.core.io.Resource 这个类的getFile()方法, 会自动获取构建resource对象带参构造中的url, 然后根据这个url确定该文件的类型. 因为在本地时调试时, 通过resource.getFile()获取的url类型的 protocol 属性为File, 所以可以自动生成文件; 然而在将项目打包成jar部署在服务器上时, 因为该文件是在jar里面的. 因此通过resource.getFile()获取的url类型的 protocol 属性为jar. 所以抛出该异常 cannot be resolved to absolute file path because it does not reside in the file system: url.

解决方案:

通过流来获取jar里面的文件,然后通过输出流将其输出.

修改前代码:

Resource resource = new ClassPathResource("tmep/xxx.txt");
File sourceFile = resource.getFile();
return FileUtils.readFileToString(sourceFile, "UTF-8");

修改后代码

 Resource resource = new ClassPathResource("tmep/xxx.txt");        
 return getFileText(resource.getInputStream());

    /**
     * 获取文件内容
     * @param inputStream
     * @return
     */
    public static String getFileText(InputStream inputStream) {
        StringBuilder textBuilder = new StringBuilder();
        try {
            Reader reader = new BufferedReader(new InputStreamReader(inputStream,
                    Charset.forName(StandardCharsets.UTF_8.name())));
            int line = 0;
            while ((line = reader.read()) != -1) {
                textBuilder.append((char) line);
            }
        } catch (IOException e) {
            log.error("getFileText error", e);
            throw new RuntimeException(e);
        }
        return textBuilder.toString();
    }

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值