ClassLoader讀取文件,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);

                //from 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(相對路徑);的形式,是找不到文件資源的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章