天天看點

Java使用ZipInputStream類(簡單)解壓縮檔案,具體方法如下:

Java使用ZipInputStream類(簡單)解壓縮檔案,具體方法如下:

package cn.oop.lh.IOs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class tests1 {

	public static void main(String[] args) {
		try {
			test6();
		} catch (Exception e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
	}

	/**
	 * 實作解壓縮方法
	 */
	public static void test6() throws Exception {
		// 1.定義需要解壓縮檔案File對象
		File src1 = new File("G:/測試檔案夾/wrod.zip");
		// 2.設定解壓縮之後的路徑
		File src2 = new File("G:/測試檔案夾" + File.separator + InterceptingFileSuffixes(src1.getName(), false));
		MyMkdirs(src2);
		// 3.定義解壓縮ZipInputStream對象
		ZipInputStream zinput = new ZipInputStream(new FileInputStream(src1));
		// 4.擷取解壓縮目錄ZipEntry對象
		ZipEntry entry = zinput.getNextEntry();
		// 5.建立指定條目(entry)檔案
		File file = new File(src2.getPath(), entry.toString());
		file.createNewFile();
		// 6.讀取寫入資料
		FileOutputStream fOutput = new FileOutputStream(file);
		byte[] bs = new byte[1024];
		while (-1 != (zinput.read(bs))) {
			fOutput.write(bs);
			System.out.println("解壓縮中.......");
		}
		// 7.釋放系統資源
		fOutput.flush();
		fOutput.close();
		zinput.close();
		System.out.println("解壓完成!!!!!!!!");
	}

	/**
	 * path代表路徑, true代表截取字元'.'之後的檔案字尾,false代表截取'.'之前的字元串
	 * 
	 * @param path
	 * @param b
	 */
	protected static String InterceptingFileSuffixes(String path, boolean b) {
		return b == true ? path.substring(path.indexOf("."), path.length()) : path.substring(0, path.indexOf("."));
	}

	/**
	 * 檢視給定的File對象檔案存不存在,如果不存在,則建構一個
	 * 
	 * @param file
	 */
	protected static void MyMkdirs(File file) {
		if (!file.exists()) {
			file.mkdirs();
			System.out.println("因為所選路徑不存在,系統預設建構指定路徑");
		} else {
			System.out.println("檔案目錄已經存在");
		}
	}
}