java读取zip中的文件,直接读取Zip文件中的文件 - Java

My situation is that I have a zip file that contains some files (txt, png, ...) and I want to read it directly by their names, I have tested the following code but no result (NullPointerExcepion):

InputStream in = Main.class.getResourceAsStream("/resouces/zipfile/test.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

resources is a package and zipfile is a zip file.

解决方案

If you can be sure that your zip file will never be packed inside another jar, you can use something like:

URL zipUrl = Main.class.getResource("/resources/zipfile.zip");

URL entryUrl = new URL("jar:" + zipUrl + "!/test.txt");

InputStream is = entryUrl.openStream();

Or:

URL zipUrl = Main.class.getResource("/resources/zipfile.zip");

File zipFile = new File(zipUrl.toURI());

ZipFile zip = new ZipFile(zipFile);

InputStream is = zip.getInputStream(zip.getEntry("test.txt"));

Otherwise, your choices are:

Use a ZipInputStream to scan through the zip file once for each entry that you need to load. This may be slow if you have a lot of resources, unless you can reuse the same ZipInputStream for all your resources.

Don't pack the resources in a nested zip file, and just inline them in the jar with the code.

Copy the nested zip file into a temporary directory, and access it using the ZipFile class.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值