1. 程式人生 > >使用commons-compress.jar壓縮ZIP檔案

使用commons-compress.jar壓縮ZIP檔案

       /**
* <p>Title: ZipUtils</p>
* <p>Description: 對檔案的壓縮和解壓工具包</p>
* <p>Company: HappyLife</p> 
* @date 2014年10月1日
 */
public class ZipUtils {

/**
* 多檔案壓縮(一級目錄檔案壓縮)
* @param files:需要壓縮的檔案
* @param destPath:壓縮檔案的路徑
*/
public static void compressFile(File[] files, String destPath) throws Exception {
if(isEndWidthZip(destPath) && files != null) {
File desFile = new File(destPath);

if(!desFile.exists()) {
desFile.getParentFile().mkdirs();
desFile.createNewFile();

}

ZipArchiveOutputStream zous = new ZipArchiveOutputStream(desFile);
zous.setUseZip64(Zip64Mode.AsNeeded);

for(File file: files) {
InputStream in = null;
if(file != null) {
in = new FileInputStream(file);
ArchiveEntry entry = new ZipArchiveEntry(file, file.getName());
zous.putArchiveEntry(entry);
IOUtils.copy(in, zous);
zous.closeArchiveEntry();
IOUtils.closeQuietly(in);
}

}
IOUtils.closeQuietly(zous);
}
}

/**
* 解壓縮檔案
* @param zipPath --需要解壓檔案的路徑
* @param filePath -- 檔案解壓後的路徑
*/
public static void decompressFile(String zipPath, String filePath) throws Exception{
if(isEndWidthZip(zipPath)) {

//獲得輸入流
ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(zipPath));
ZipArchiveEntry entry = null;
while((entry = zin.getNextZipEntry()) != null) {
String fileName = entry.getName();
File file = new File(filePath, fileName);
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
IOUtils.copy(zin, out);
IOUtils.closeQuietly(out);
}
IOUtils.closeQuietly(zin);
}
}

/**
* 判斷設定的儲存檔案的路徑名字尾是否為.zip/.ZIP
* @param destPath
* @return
*/
public static boolean isEndWidthZip(String destPath) {
boolean flag =  false;
if(destPath != null) {
if(destPath.endsWith(".ZIP") || destPath.endsWith(".zip")) {
flag = true;
}
}
return flag;
}
}