jar:file:/D:/test/test/.metadata/.plugins/org.eclipse.wst.server.core/test/test/test/WEB-INF/lib/test-0.0.1-SNAPSHOT.jar!/ca.crt

在你的项目中可能经常会使用 ClassLoader.getSystemResourceAsStream 等方法来读取一个文件内容,使用 properties 来读取。
但是当你打包后会发现你程序出现了问题,这个时候怎么办呢?
** 解决 ** 可以尝试一下以下的代码来获取文件,内容可自行修改,逻辑比较简单,就是获取相对地址然后得到文件

   //s是地址+文件名 from fhadmin.cn
   private File loadNewFromResources(String s) {
       File file = new File( s);
 
        try {
            if (!file.exists()) {
                file.createNewFile();
 
                InputStream fileInput = SampleServerStartup.class.getClassLoader().getResourceAsStream( s);
 
                //java项目大全 fhadmin.cn
                //file = File.createTempFile(s,"");
                System.out.println(file.getPath());
                System.out.println(file.getCanonicalPath());
                System.out.println(file.getName());
                //System.out.println("length:"+fileInput.available());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
 
                while ((len = fileInput.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                fileInput.close();
 
                //System.out.println(content); //from fhadmin.cn
 
                FileOutputStream fileout = new FileOutputStream(file);
                baos.writeTo(fileout);
 
                baos.close();
                fileout.close();
 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

为什么要这样处理,因为在你打包后通过 File f=new File (“上述路径 — 相对路径”); 来获取文件时会发现 FileNotFoundException

可以通过 getResourceAsStream()读取到文件流 — 只可读取

因为这不是文件资源定位符的格式 (在 jar 中资源有其专门的 URL 格式为: jar:!/{entry} )。
如果 jar 包中的类源代码用 File f=new File (相对路径); 的形式,是找不到文件资源的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐