直接读取Zip文件中的文件 - Java [英] Read directly a file within a Zip file - Java

查看:1099
本文介绍了直接读取Zip文件中的文件 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是我有一个包含一些文件(txt,png,...)的zip文件,我想直接用它们的名字来读它,我测试了下面的代码,但没有结果(NullPointerExcepion):

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"));

资源是一个包, zipfile 是一个zip文件。

resources is a package and zipfile is a zip file.

推荐答案

如果你可以确定你的zip文件永远不会被打包到另一个jar中,你可以使用一些东西喜欢:

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();

或者:

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"));

否则,您的选择是:


  • 使用ZipInputStream为您需要加载的每个条目扫描一次zip文件。如果您拥有大量资源,这可能会很慢,除非您可以为所有资源重用相同的ZipInputStream。

  • 不要将资源打包到嵌套的zip文件中,只是内联它们在带有代码的jar中。

  • 将嵌套的zip文件复制到一个临时目录中,并使用ZipFile类访问它。

这篇关于直接读取Zip文件中的文件 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆