Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read files from Zip file to memory with Java?

Tags:

java

zip

unzip

I found example from SUN site (http://java.sun.com/developer/technicalArticles/Programming/compression/), but it returns BufferedOutputStream. But I would like to get ZipEntry file as InputStream and then process next file. Is that possible? My program has no access to harddisk, so it cannot even temporarily save files.

import java.io.*;
import java.util.zip.*;

public class UnZip {
   final int BUFFER = 2048;
   public static void main (String argv[]) {
      try {
         BufferedOutputStream dest = null;
         FileInputStream fis = new 
       FileInputStream(argv[0]);
         ZipInputStream zis = new 
       ZipInputStream(new BufferedInputStream(fis));
         ZipEntry entry;
         while((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " +entry);
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new 
          FileOutputStream(entry.getName());
            dest = new 
              BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) 
              != -1) {
               dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
         }
         zis.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
like image 331
newbie Avatar asked Sep 04 '11 12:09

newbie


1 Answers

Well, just change the part that writes the file into something you want to do with the data.

while((entry = zis.getNextEntry()) != null) {
    System.out.println("Extracting: " + entry);
    int count;
    byte[] data = new byte[BUFFER];
    String filename = entry.getName();
    System.out.println("Filename: " + filename);
    while ((count = zis.read(data, 0, BUFFER)) != -1) {
       // Do whatever you want with the data variable
       System.out.println(data);
    }
}
like image 96
CodeCaster Avatar answered Sep 18 '22 01:09

CodeCaster