How to read content of the Zipped file without extracting in java

浪子不回头ぞ 提交于 2019-11-29 07:28:54
user000001

Try this:

        ZipFile fis = new ZipFile("ex.zip");

        int i = 0;
        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            System.out.println(entry);
            System.out.println(i);

            InputStream in = fis.getInputStream(entry);

        }

For example, if the file contains text, and you want to print it as a String, you can read the InputStream like this: Read/convert an InputStream to a String

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:

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

If you have Java 1.7:

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

otherwise use Appache.commons lib

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

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

I think that in your case the fact that a zipfile is a container that can hold many files (and thus forces you to navigate to the right contained file each time you open it) seriously complicates things, as you state that each zipfile only contains one textfile. Maybe it's a lot easier to just gzip the text file (gzip is not a container, just a compressed version of your data). And it's very simple to use:

GZIPInputStream gis = new GZIPInputStream(new FileInputStream("file.txt.gz"));
// and a BufferedReader on top to comfortably read the file
BufferedReader in = new BufferedReader(new InputStreamReader(gis) );

Producing them is equally simple:

GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("file.txt.gz"));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!