java工程内部文件路径读取问题jar:file:\No such file or directory

今天发现一个问题,在本地的开发环境下可以读取.pptx文件。但是部署到测试环境或者开发环境就会报错,因为此时这个.pptx文件被打成jar包了。导致读取文件时无法读取。一旦被打入jar包,path就变为了jar:file:\usr\local\product\jar\product-controller-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\template\service_proposal_template.pptx,从而无法读取到对应jar中的文件地址。

通过以下这种方式去获取工程文件中的资源地址


        URL classPath = Thread.currentThread().getContextClassLoader().getResource("");
        //模板文件路径
        String proFilePath = classPath.toString();
        //移除开通的file:/六个字符
        proFilePath = proFilePath.substring(6) + "template/" + ProductContant.SERVICE_PROPOSAL_TEMPLATE_NAME + ".pptx";

        File file = new File(proFilePath);

        InputStream powerPoint = new FileInputStream(file);


会报如下错误:


2017-12-12 12:16:19.181 ERROR com.xxx.product.application.ControllerAdvice 24 errorHandler -- le:/usr/local/product/jar/product-controller-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/template/service_proposal_template.pptx (No such file or directory)

exception='java.io.FileNotFoundException: le:/usr/local/atme-product/jar/atme-product-controller-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/template/service_proposal_template.pptx (No such file or directory)

扫描二维码关注公众号,回复: 1038701 查看本文章


解决方案:

不读取工程中的文件地址,直接将对应文件转化为二进制流进行操作。

InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/service_proposal_template.pptx");
InputStream powerPoint = new FileInputStream(is);





猜你喜欢

转载自blog.csdn.net/ccmedu/article/details/78783248