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");
}
returnreqFile;
}
One Comment
Thanks for your post..