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

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
234
粉丝
11
喜欢
34
收藏
35
排名:793
访问:8674
私信
所有博文
社区赞助商