Working with Zip file in java

Following are the code snippets to retrieve a zip file from the inputstream(which can obtained from FileItem) and retrieve a file named file.txt from the zip file.

Retrieving a zipfile from inputstream

private ZipFile getZipFileFromStream(InputStream inputStream, String inputFileName) throws IOException {

BufferedOutputStream outputStream = null;
ZipFile zipFile = null;
byte[] buffer = new byte[1024];
int len;

try {

outputStream = new BufferedOutputStream(new FileOutputStream(inputFileName));
while ((len = inputStream.read(buffer)) >= 0) {

outputStream.write(buffer, 0, len);

}
outputStream.close();
File inputFile = new File(inputFileName);
zipFile = new ZipFile(inputFile, ZipFile.OPEN_READ);

} catch (IOException e) {//if the submitted file is an invalid zip file

throw new IOException("Invalid Zip File");

}finally{

if (outputStream != null){
outputStream.close();
}

}

return zipFile;

}

Retrieve a file from the zipfile

private File retrieveIndexFile(ZipFile zipFile) throws IOException{

ZipEntry entry = zipFile.getEntry("file.txt");
BufferedOutputStream indexFileOutStream = null;
byte[] buffer = new byte[1024];
int len;
File reqFile = null;

try {

InputStream indexFileStream = zipFile.getInputStream(entry);
indexFileOutStream = new BufferedOutputStream(new FileOutputStream("file.txt"));
while ((len = indexFileStream.read(buffer)) >= 0) {

indexFileOutStream.write(buffer, 0, len);

}
indexFileOutStream.close();
reqFile = new File("file.txt");

} catch (IOException e) {

throw new IOException("Fatal error when retreiving index file");

}

return reqFile ;

}

Advertisement

One Comment

  1. CM
    Posted December 27, 2006 at 11:43 am | Permalink | Reply

    Thanks for your post..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.