[java] zip工具类

package com.szwx.credit.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtil {

    public ZipUtil() {
    }

    public void CreateZipFile(String filePath, String zipFilePath) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipFilePath);
            zos = new ZipOutputStream(fos);
            
            writeZipFile(new File(filePath), zos, "");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zos != null)
                    zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void writeZipFile(File f, ZipOutputStream zos, String hiberarchy) {
        if (f.exists()) {
            if (f.isDirectory()) {
                hiberarchy += f.getName() + "/";
                File[] fif = f.listFiles();
                for (int i = 0; i < fif.length; i++) {
                    writeZipFile(fif[i], zos, hiberarchy);
                }

            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(f);
                    ZipEntry ze = new ZipEntry(hiberarchy + f.getName());
                    zos.putNextEntry(ze);
                    zos.setEncoding("gbk");  
                    byte[] b = new byte[1024];
                    while (fis.read(b) != -1) {
                        zos.write(b);
                        b = new byte[1024];
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fis != null)
                            fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

    }

    private static ZipUtil zu = null;

    public static ZipUtil getInstance() {
        if (zu == null)
            zu = new ZipUtil();
        return zu;

    }

    public static void main(String[] args) {

        ZipUtil.getInstance().CreateZipFile("D:/My Documents/jquery",
                "d:/test.zip");
    }

}

 

posted @ 2015-02-14 21:40  snow__wolf  阅读(196)  评论(0)    收藏  举报