1. 程式人生 > >java解壓zip檔案例項

java解壓zip檔案例項

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

/**
 * zip解壓程式
 */
public class test3 {

      
    public static void main(String[] args) throws Exception { 
    	//要解壓的目錄
    	File file = new File("F:\\java\\");
    	//ZipFile是ant.jar裡面的物件
    	ZipFile zipFile = new ZipFile("F:\\java\\xmlobj.rar","GBK");
		Enumeration en = zipFile.getEntries();
    	//ZipEntry是ant.jar裡面的物件
		ZipEntry zipEntry = null;
		try {
			while (en.hasMoreElements()) {
				boolean isExist = true;//檔案和資料夾是否存在
				zipEntry = (ZipEntry) en.nextElement();
				if (zipEntry.isDirectory()) {//如果是目錄
					String dirName = zipEntry.getName();
					dirName = dirName.substring(0, dirName.length() - 1);
					File f = new File(file.getPath() + File.separator + dirName);
					f.mkdirs();
				} else {
					String strFilePath = file.getPath() + File.separator
							+ zipEntry.getName();
					File f = new File(strFilePath);

					// 判斷檔案不存在的話,就建立該檔案所在資料夾的目錄
					if (!f.exists()) {
						isExist = false;
						String[] arrFolderName = zipEntry.getName().split("/");
						String strRealFolder = "";
						for (int i = 0; i < (arrFolderName.length - 1); i++) {
							strRealFolder += arrFolderName[i] + File.separator;
						}
						strRealFolder = file.getPath() + File.separator
								+ strRealFolder;
						File tempDir = new File(strRealFolder);
						// 此處使用.mkdirs()方法,而不能用.mkdir()
						tempDir.mkdirs();
					}
					//建立檔案
					f.createNewFile();
					InputStream in = zipFile.getInputStream(zipEntry);
					FileOutputStream out = new FileOutputStream(f);
					try {
						int c;
						byte[] by = new byte[1024];
						while ((c = in.read(by)) != -1) {
							out.write(by, 0, c);
						}
						out.flush();
					} catch (IOException e) {
						throw e;
					} finally {
						out.close();
						in.close();
					}
				}
			}
		} catch (IOException e) {
			throw e;
		}finally{
			zipFile.close();
		}
    } 


}