springboot 打 jar 包后读取不到文件

550阅读 0评论2022-05-12 fhadmin
分类:Java


点击(此处)折叠或打开


  1. 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

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

  5.    //s是地址+文件名 from fhadmin.cn
  6.    private File loadNewFromResources(String s) {
  7.        File file = new File( s);
  8.  
  9.         try {
  10.             if (!file.exists()) {
  11.                 file.createNewFile();
  12.  
  13.                 InputStream fileInput = SampleServerStartup.class.getClassLoader().getResourceAsStream( s);
  14.  
  15.                 //java项目大全 fhadmin.cn
  16.                 //file = File.createTempFile(s,"");
  17.                 System.out.println(file.getPath());
  18.                 System.out.println(file.getCanonicalPath());
  19.                 System.out.println(file.getName());
  20.                 //System.out.println("length:"+fileInput.available());
  21.                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
  22.                 byte[] buffer = new byte[1024];
  23.                 int len = 0;
  24.  
  25.                 while ((len = fileInput.read(buffer)) != -1) {
  26.                     baos.write(buffer, 0, len);
  27.                 }
  28.                 fileInput.close();
  29.  
  30.                 //System.out.println(content); //from fhadmin.cn
  31.  
  32.                 FileOutputStream fileout = new FileOutputStream(file);
  33.                 baos.writeTo(fileout);
  34.  
  35.                 baos.close();
  36.                 fileout.close();
  37.  
  38.             }
  39.         } catch (IOException e) {
  40.             e.printStackTrace();
  41.         }
  42.         return file;
  43.     }

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

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

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


上一篇:java WebSocket 即时通讯服务端代码
下一篇:springboot 配置 https