Thursday, October 18, 2012

Reading ZipEntry content from ZipInputStream

Context:

Java
MySQL
Zip

Problem:

I needed to search the content of a specific file in the Zip which was read in from the database.  I had no direct access to the Zip file except to the input stream of the Zip file.

Solution:

InputStream inStream = blob.getBinaryStream();  
// the blob contains the zip

ZipInputStream zipInStream = new ZipInputStream(inStream);

ZipEntry zipEntry = null;
while((zipEntry = zipInStream.getNextEntry()) != null) {
  String filename = zipEntry.getName();
  if(filename.matches("file_name_that_i_want_to_look_at") {
    StringWriter writer = new StringWriter();
    int i;
    while((i = zipInStream.read()) !=  -1) {
         writer.write(i);   
    } 

    String content = writer.toString();  // content of the file
  }
}

No comments:

Post a Comment