Java zip解壓工具類

分享一個自己用的zip工具類

public class ZipUtils {
	 public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
		 
		         long start = System.currentTimeMillis();
		         // 判斷源文件是否存在
		         if (!srcFile.exists()) {
		             throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
		         }
		         // 開始解壓
		         ZipFile zipFile = null;
		         try {
		             zipFile = new ZipFile(srcFile);
		             Enumeration<?> entries = zipFile.entries();
		             while (entries.hasMoreElements()) {
		                 ZipEntry entry = (ZipEntry) entries.nextElement();
		                 System.out.println("解壓" + entry.getName());
		                 // 如果是文件夾,就創建個文件夾
		                 if (entry.isDirectory()) {
		                     String dirPath = destDirPath + "/" + entry.getName();
		                     File dir = new File(dirPath);
		                     dir.mkdirs();
		                 } else {
		                     // 如果是文件,就先創建一個文件,然後用io流把內容copy過去
		                     File targetFile = new File(destDirPath + "/" + entry.getName());
		                     // 保證這個文件的父文件夾必須要存在
		                     if(!targetFile.getParentFile().exists()){
		                         targetFile.getParentFile().mkdirs();
		                     }
		                     targetFile.createNewFile();
		                     // 將壓縮文件內容寫入到這個文件中
		                     InputStream is = zipFile.getInputStream(entry);
		                     FileOutputStream fos = new FileOutputStream(targetFile);
		                    int len;
		                     byte[] buf = new byte[1024];
		                     while ((len = is.read(buf)) != -1) {
		                         fos.write(buf, 0, len);
		                     }
		                     // 關流順序,先打開的後關閉
		                     fos.close();
		                     is.close();
		                 }
		             }
		             long end = System.currentTimeMillis();
		             System.out.println("解壓完成,耗時:" + (end - start) +" ms");
		         } catch (Exception e) {
		             throw new RuntimeException("unzip error from ZipUtils", e);
		         } finally {
		             if(zipFile != null){
		                 try {
		                     zipFile.close();
		                 } catch (IOException e) {
		                     e.printStackTrace();
		                 }
		             }
		         }
		     }
	 public static void main(String args[]) {
		 File zip = new File("F:/data.zip");
	    	File outputDir = new File("F:/");
	    	unZip(zip,"F:/datecopy");
	 }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章