• SpringBoot 项目打包后获取不到resource下资源的解决


    SpringBoot 项目打包后获取不到resource下资源的解决

    在项目中有几个文件需要下载,然后不想暴露真实路径,又没有CDN,便决定使用接口的方式来获取文件。最初的时候使用了传统的方法来获取文件路径,发现不行。查找资料后发现是SpringBoot框架导致的,得用另外的方法:

    //听说在linux系统中会失效。
    //不用听说了,就是会挂,血的教训
    String path = ResourceUtils.getURL("classpath:").getPath();
    
    //此方法返回读取文件字节的方式在linux系统中无异。
    InputStream inputStream  = getClass().getClassLoader().getResourceAsStream("RSA/privateKey.txt");
    
    //声明io的resources对象也可访问
    Resource resource = new ClassPathResource(uploadPath+privateKeyFileName);
    
    // 此方法用来写文件或上传文件在本项目中指定路径。
    String privateKeyFileStr = request.getSession().
        		getServletContext().getRealPath("RSA/privateKey.txt"); 
    

    刚开始的时候用的就是第一种方法,初生牛犊不怕虎吧,说不定在linux上就行呢,本地环境测试通过,然后再上linux测试环境,不出意外,挂了。

    //听说在linux系统中会失效。
    //不用听说了,就是会挂,血的教训
    String path = ResourceUtils.getURL("classpath:").getPath();
    

    乖乖使用其他的方法,这里选择使用了第三种方法:

    public byte[] downloadServerCrt() {
    	try {
    		Resource resource = new ClassPathResource("static/syslog/cert/server.crt");
    		byte[] bytes = readFileInBytesToString(resource);
    		return bytes;
    	} catch (Exception e) {
    		throw new Exception("下载失败" + e.getMessage());
    	}
    }
    

    这里还有一个坑,也是踩过了才知道,这边的resource是Resource类型的变量,刚开始我使用了resource.getFile()方法获取到File对象然后再采用IO流进行操作,即:

    File file = resource.getFile();
    DataInputStream isr = new DataInputStream(resource.getInputStream());
    ...
    

    在IDE中运行是完全没有问题的,但使用mvn打包成jar包后,再运行就会提示ERROR:

    java.io.FileNotFoundException: class path resource [static/syslog/cert/server.crt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/admin/dtlog-web/lib/log-web-3.0.2.jar!/static/syslog/cert/server.crt
    

    后来查阅了资料说:一旦打成jar包后,使用File是访问不到资源的内容的,推荐使用getInputStream()的方法,修改后:

    InputStream in = resource.getInputStream();
    DataInputStream isr = new DataInputStream(in);
    ...
    

    测试没有问题,bug解决。

    参考资料

    Springboot 访问resources目录文件方式

    Classpath resource not found when running as jar

  • 相关阅读:
    平面切圆柱面的椭圆绘制
    抛物面倾斜体积积分
    计算误差函数的积分--erf(x)
    三棱椎的体积
    Mac平台上OpenCV开发环境搭建
    仿新浪右下角视频弹窗(视频弹出广告)播放器
    python爬虫之Scrapy 使用代理配置
    ip地址定位库
    python 使用 redis expire属性设置访问时间间隔
    如何做将两张图片合二为一
  • 原文地址:https://www.cnblogs.com/yisany/p/10228719.html
Copyright © 2020-2023  润新知