1. 程式人生 > 其它 >springboot 打 jar 包後讀取不到檔案

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