springboot 打 jar 包后读取不到文件

发布时间:2022-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了springboot 打 jar 包后读取不到文件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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 (相对路径); 的形式,是找不到文件资源的。

脚本宝典总结

以上是脚本宝典为你收集整理的springboot 打 jar 包后读取不到文件全部内容,希望文章能够帮你解决springboot 打 jar 包后读取不到文件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: