2012年7月18日 星期三

How to decompress an zip file with full folder structure


如何用 java 解壓一個 zip 檔




previously, I write an example about how to zip a folder and keep it original folder structure, 


but how to extract a zip file in java and keep it's original structure?

here is a code snippet--


org.apache.commons.compress.archivers.zip.ZipFile zf = new org.apache.commons.compress.archivers.zip.ZipFile(zipFile);
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream inputStream = new ZipInputStream(fis);

// Loop through all the files and folders
int exttactCount = 0;
progressDialog.setMax(fileCount);
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry()) {
String innerFileName = GlobalConfig.getAlbumFolder() + entry.getName();
File innerFile = new File(innerFileName);
if (innerFile.exists()) {
innerFile.delete();
}

// Check if it is a folder
if (entry.isDirectory()) {
// Its a folder, create that folder
innerFile.mkdirs();
} else {
// Create a file output stream
FileOutputStream outputStream = new FileOutputStream(innerFileName);
final int BUFFER = 2048;

// Buffer the ouput to the file
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream, BUFFER);

// Write the contents
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
bufferedOutputStream.write(data, 0, count);
}

bufferedOutputStream.flush();
bufferedOutputStream.close();

}

inputStream.closeEntry();

}
inputStream.close();

ps: I really like to use apache common library.

2 則留言:

  1. That is a good tip particularly to those fresh to
    the blogosphere. Short but very accurate information?
    Thank you for sharing this one. A must read article!


    Feel free to visit my web blog ... His explanation

    回覆刪除
  2. Nice response in return of this difficulty with real arguments
    and describing all concerning that.

    Visit my web page: Click here

    回覆刪除