1. 程式人生 > >java程式碼實現檔案或資料夾的壓縮和解壓

java程式碼實現檔案或資料夾的壓縮和解壓

這裡寫了個工具類,可以實現檔案的壓縮和解壓功能。

package com.cntaiping.tpi.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import java.util.zip.ZipOutputStream;

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

public class ZipUtils {

	/**
     * zip解壓
     * 
     * @param zipfile
     *            File 需要解壓縮的檔案
     * @param descDir
     *            String 解壓後的目標目錄
	 * @throws IOException 
     */
    public static void unZipFiles(java.io.File zipfile, String descDir) throws IOException{
    	 File pathFile = new File(descDir);
	        if (!pathFile.exists())
	        {
	            pathFile.mkdirs();
	        }
	        ZipFile zip = new ZipFile(zipfile);
	        for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();)
	        {
	            ZipEntry entry = (ZipEntry) entries.nextElement();
	            String zipEntryName = entry.getName();
	            InputStream in = zip.getInputStream(entry);
	            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
	 
	            //獲取當前file的父路徑,這才是資料夾
	            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
	             
	            // 判斷路徑是否存在,不存在則建立檔案路徑
	            if (!file.exists())
	            {
	                file.mkdirs();
	            }
	            // 判斷檔案全路徑是否為資料夾,如果是上面已經上傳,不需要解壓
	            if (new File(outPath).isDirectory())
	            {
	                continue;
	            }
	            OutputStream out = new FileOutputStream(outPath);
	            byte[] buf1 = new byte[1024];
	            int len;
	            while ((len = in.read(buf1)) > 0)
	            {
	                out.write(buf1, 0, len);
	            }
	            in.close();
	            out.close();
	        }
    	
    }
    /**
     * 壓縮指定的單個或多個檔案,如果是目錄,則遍歷目錄下所有檔案進行壓縮
     * @param zipFileName ZIP檔名包含全路徑
     * @param files  檔案列表
     */
	public static void createZip(String zipFileName, File files)	throws Exception {
		ZipOutputStream zipOut = null;
		FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(zipFileName);
			zipOut = new ZipOutputStream(fileOut);
			if (null != files) {
				zip(zipOut, files, files.getName());
			}
			zipOut.close(); // 輸出流關閉
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(null!=zipOut){
				zipOut.close();
			}
			if(null!=fileOut){
				fileOut.close();
			}
		}

	}
 
    /**
     * 執行壓縮
     * @param out ZIP輸入流
     * @param f   被壓縮的檔案
     * @param base  被壓縮的檔名
     */
	private static void zip(ZipOutputStream out, File f, String base)
			throws Exception { // 方法過載
		FileInputStream in = null;
		BufferedInputStream bi = null;
		try {
			if (f.isDirectory()) {// 壓縮目錄
				File[] fl = f.listFiles();
				if (fl.length == 0) {
					out.putNextEntry(new ZipEntry(base + "/")); // 建立zip實體
				}
				for (int i = 0; i < fl.length; i++) {
					zip(out, fl[i], base + "/" + fl[i].getName()); // 遞迴遍歷子資料夾
				}
			} else { // 壓縮單個檔案
				out.putNextEntry(new ZipEntry(base)); // 建立zip實體
				in = new FileInputStream(f);
				bi = new BufferedInputStream(in);
				byte[] bufs = new byte[1024 * 10];
				int read = 0;
				while ((read = bi.read(bufs, 0, 1024 * 10)) != -1) {
					out.write(bufs, 0, read);
				}
				out.closeEntry(); // 關閉zip實體
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (null != bi) {
				bi.close();
			}
			if (null != in) {
				in.close();
			}
		}
	}
	/**
	 * 獲取檔案大小  單位為位元組
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static long getFileSize(String filePath) throws Exception{
		FileChannel fc= null;
		FileInputStream fis=null;
		long fileSize=0;
		try {
			File f= new File(filePath);
			if (f.exists() && f.isFile()){
			     fis= new FileInputStream(f);
				fc= fis.getChannel();
				fileSize=fc.size();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if(null!= fis){
				fis.close();
			}
			if (null!=fc){
				fc.close();
			} 
		}
		return fileSize;
	}	
}