Java實現Zip壓縮包解壓


    對zip壓縮包的解壓是比較常見的應用場景,java代碼的實現也很簡單。廢話不多說,直接上代碼吧
一、代碼
	/**
	 * zip解壓  
	 * @param srcFile        zip源文件
	 * @param destDirPath	  解壓后的目標文件夾
	 * @throws RuntimeException 解壓失敗會拋出運行時異常
	 */
	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[BUFFER_SIZE];
					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();
				}
			}
		}
	}

二、小結
    解壓的代碼並不復雜,不過有個關鍵點是:創建文件時,需要保證該文件所在的文件夾必須存在。
    如果對Java實現zip壓縮感興趣,可看我上一篇博客: http://www.cnblogs.com/zeng1994/p/7862288.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM