美文网首页
服务部署后读取Jar包内资源遇到文件找不到的问题

服务部署后读取Jar包内资源遇到文件找不到的问题

作者: 楚骧 | 来源:发表于2016-12-23 14:27 被阅读0次

    我们在开发环境的IDE内能顺利的跑通下面的读取资源文件的方法,但是服务部署到测试环境后会出现文件找不到的问题。

    String filePath = this.getClass().getResource("/resource/hello.zip").getFile();
    File file = new File(filePath);
    ...
    

    部署到测试环境后,发现filePath的值变成了:

    file:/disk1/webroot/WEB-INF/lib/service.jar!/resource/hello.zip

    显然Java的文件系统不认识这样的文件路径,所以会包文件找不到的错误。如果我们需要在运行的时候用到Resource中的文件,只有一种办法,就是用以下方法获取文件的InputStream,然后将文件用流的方式读取到内存,然后再使用,或者通过流的方式将Resource中的文件复制到文件系统其他位置,再读取。下面是从jar包中通过流的方式将文件复制到文件系统其他位置的参考代码:

    public static void copyResourceFileToFolder(String resourceName , String targetFilePath){
        InputStream is = null;
        FileOutputStream os = null;
        try {
            is = ResourceUtil.class.getClassLoader().getResourceAsStream(getCPResourcePath(resourceName));
    
            if (is != null) {
                os = new FileOutputStream(targetFilePath);
    
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
            }
        }
        catch (IOException ex2){
            throw new RuntimeException(ex2);
        }
        finally {
            if(null != is){
                try {
                    is.close();
                }
                catch (IOException ex2){
                    throw new RuntimeException(ex2);
                }
            }
    
            if(null != os){
                try {
                    os.close();
                }
                catch (IOException ex2){
                    throw new RuntimeException(ex2);
                }
            }
        }
    }

    相关文章

      网友评论

          本文标题:服务部署后读取Jar包内资源遇到文件找不到的问题

          本文链接:https://www.haomeiwen.com/subject/qbskvttx.html