How to read Zipped file contents without extracting in java

I have a file with type names ex.zip. In this example, the zip file contains only one file with the same name (for example, `ex.txt '), which is quite large. I do not want to extract the zip file every time. I need to read the contents of a file (ex.txt) without extracting the zip file. I tried code like below. But I can only read the file name in a variable.

How can I read the contents of a file and save it in a variable?

Thanks at Advance

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
}
+5
source share
3 answers

Your idea is to read the zip file as it is into an array of bytes and store it in a variable. Later, when you need a zip, you retrieve it on demand, preserving memory:

Zip zipFileBytes

Java 1.7:

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

Appache.commons lib

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

Zip zipFileBytes, .

, -,

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

:

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

        }

, , InputStream : / InputStream

+4

I think that in your case, the fact that the zipfile is a container that can store many files (and thus makes you navigate the right contents of the file every time you open it) makes the situation more complicated, as you state that each zip file contains only one text file. Maybe it’s a lot easier to just gzip a text file (gzip is not a container, but only a compressed version of your data). And this is a very simple 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) );

The product of them is equally simple:

GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("file.txt.gz"));
+2
source

All Articles