Chinaunix首页 | 论坛 | 博客
  • 博客访问: 535331
  • 博文数量: 298
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 3077
  • 用 户 组: 普通用户
  • 注册时间: 2019-06-17 10:57
文章分类

全部博文(298)

文章存档

2022年(96)

2021年(201)

2019年(1)

我的朋友

分类: Java

2021-08-27 11:55:36

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来读取。
但是当你打包后会发现你程序出现了问题,这个时候怎么办呢?
**解决**可以尝试一下以下的代码来获取文件,内容可自行修改,逻辑比较简单,就是获取相对地址然后得到文件

点击(此处)折叠或打开

  1. //s是地址+文件名 from fhadmin.cn
  2.    private File loadNewFromResources(String s) {
  3.        File file = new File( s);

  4.         try {
  5.             if (!file.exists()) {
  6.                 file.createNewFile();

  7.                 InputStream fileInput = SampleServerStartup.class.getClassLoader().getResourceAsStream( s);

  8.                 //from fhadmin.cn
  9.                 //file = File.createTempFile(s,"");
  10.                 System.out.println(file.getPath());
  11.                 System.out.println(file.getCanonicalPath());
  12.                 System.out.println(file.getName());
  13.                 //System.out.println("length:"+fileInput.available());
  14.                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
  15.                 byte[] buffer = new byte[1024];
  16.                 int len = 0;

  17.                 while ((len = fileInput.read(buffer)) != -1) {
  18.                     baos.write(buffer, 0, len);
  19.                 }
  20.                 fileInput.close();

  21.                 //System.out.println(content); //from fhadmin.cn

  22.                 FileOutputStream fileout = new FileOutputStream(file);
  23.                 baos.writeTo(fileout);

  24.                 baos.close();
  25.                 fileout.close();

  26.             }
  27.         } catch (IOException e) {
  28.             e.printStackTrace();
  29.         }
  30.         return file;
  31.     }


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


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

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

阅读(872) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~