1. 程式人生 > >zip檔案解壓工具類

zip檔案解壓工具類

java解壓zip檔案

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import
java.util.zip.CheckedInputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; public class MyZipUtil { /** * 解壓zip檔案 * @throws IOException */ public static String unZIP(String zipPath,String outPath ){ ZipFile zipFile=null;
try { zipFile = new ZipFile(zipPath,"GBK"); //壓縮檔案的實列,並設定編碼 //獲取壓縮文中的所以項 for(Enumeration<ZipEntry> enumeration = zipFile.getEntries();enumeration.hasMoreElements();) { OutputStream os = null; BufferedOutputStream bos
=null; InputStream is =null; BufferedInputStream bis =null; CheckedInputStream cos =null; ZipEntry zipEntry = null; try { zipEntry = enumeration.nextElement();//獲取元素 //排除空資料夾 if(!zipEntry.getName().endsWith(File.separator)) { System.out.println("正在解壓檔案:"+zipEntry.getName());//列印輸出資訊 //建立解壓目錄 File f = new File(outPath); //判斷是否存在解壓目錄 if(!f.exists()) { f.mkdirs();//建立解壓目錄 } os = new FileOutputStream(outPath+zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/")+1));//建立解壓後的檔案 bos = new BufferedOutputStream(os);//帶緩的寫出流 is = zipFile.getInputStream(zipEntry);//讀取元素 bis = new BufferedInputStream(is);//讀取流的快取流 cos = new CheckedInputStream(bis, new CRC32());//檢查讀取流,採用CRC32演算法,保證檔案的一致性 byte [] b = new byte[1024*8];//位元組陣列,每次讀取1024個位元組 //迴圈讀取壓縮檔案的值 while(cos.read(b)!=-1) { bos.write(b);//寫入到新檔案 } bos.flush(); os.flush(); } else { //如果為空資料夾,則建立該資料夾 new File(outPath+zipEntry.getName()).mkdirs(); } } catch (Exception e) { return "1"; }finally { if(cos!=null){ cos.close(); } if(bis!=null){ bis.close(); } if(is!=null){ is.close(); } if(bos!=null){ bos.close(); } if(os!=null){ os.close(); } if(zipEntry!=null){ zipEntry.clone(); } } } System.out.println("解壓完成"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }finally { try { zipFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "0"; } }