如何在不提取java的情况下读取Zipped文件的内容 [英] How to read content of the Zipped file without extracting in java

查看:91
本文介绍了如何在不提取java的情况下读取Zipped文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件名为 ex.zip 。在这个例子中,Zip文件只包含一个具有相同名称的文件(即ex.txt),这个文件非常大。我不想每次都提取zip文件。因此我需要在不解压缩zip文件的情况下读取文件的内容(ex.txt)。我尝试了下面的一些代码但是我只能读取变量中文件的名称。

I have file with names like ex.zip. In this example, the Zip file contains only one file with the same name(ie. `ex.txt'), which is quite large. I don't want to extract the zip file every time.Hence I need to read the content of the file(ex.txt) without extracting the zip file. I tried some code like below But i can only read the name of the file in the variable.

如何读取文件的内容并将其存储在变量中?

How do I read the content of the file and stores it in the variable?

先谢谢你了

fis=new FileInputStream("C:/Documents and Settings/satheesh/Desktop/ex.zip");
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;

while((entry = zis.getNextEntry()) != null) {
    i=i+1; 
    System.out.println(entry);
    System.out.println(i);
    //read from zis until available
}


推荐答案

您的想法是将zip文件读入字节数组并将其存储在变量中。
稍后当你需要zip时你可以按需提取它,节省内存:

Your idea is to read the zip file as it is into a byte array and store it in a variable. Later when you need the zip you extract it on demand, saving memory:

首先在字节数组中读取Zip文件的内容 zipFileBytes

First read the content of the Zip file in a byte array zipFileBytes

如果你有Java 1.7:

If you have Java 1.7:

Path path = Paths.get("path/to/file");
byte[] zipFileBytes= Files.readAllBytes(path);

否则使用Appache.commons lib

otherwise use Appache.commons lib

byte[] zipFileBytes;
zipFileBytes = IOUtils.toByteArray(InputStream input);

现在你的Zip文件存储在变量zipFileBytes中,仍然是压缩形式。

Now your Zip file is stored in a variable zipFileBytes, still in compressed form.

然后当你需要提取一些东西时使用

Then when you need to extract something use

ByteArrayInputStream bis = new ByteArrayInputStream(zipFileBytes));
ZipInputStream zis = new ZipInputStream(bis);

这篇关于如何在不提取java的情况下读取Zipped文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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