com.mc.printer.model.utils.ZipHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.mc.printer.model.utils.ZipHelper.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mc.printer.model.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author woderchen@163.com
 */
public class ZipHelper {

    private static final Logger log = LoggerFactory.getLogger(ZipHelper.class);

    private ZipHelper() {
    }

    public static void unZip(String sourceZip, String outDirName) throws IOException {
        log.info("unzip source:" + sourceZip);
        log.info("unzip to :" + outDirName);
        ZipFile zfile = new ZipFile(sourceZip);
        System.out.println(zfile.getName());
        Enumeration zList = zfile.entries();
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        while (zList.hasMoreElements()) {
            //ZipFileZipEntry
            ze = (ZipEntry) zList.nextElement();
            if (ze.isDirectory()) {
                continue;
            }
            //ZipEntry?InputStreamOutputStream
            File fil = getRealFileName(outDirName, ze.getName());

            OutputStream os = new BufferedOutputStream(new FileOutputStream(fil));
            InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
            int readLen = 0;
            while ((readLen = is.read(buf, 0, 1024)) != -1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();
            log.debug("Extracted: " + ze.getName());
        }
        zfile.close();

    }

    /**
     * jar????
     *
     * @param jar ????jar
     * @param subDir jar???????
     * @param loc ????
     * @param force ????
     * @return
     */
    public static boolean unZip(String jar, String subDir, String loc, boolean force) {
        try {
            File base = new File(loc);
            if (!base.exists()) {
                base.mkdirs();
            }

            ZipFile zip = new ZipFile(new File(jar));
            Enumeration<? extends ZipEntry> entrys = zip.entries();
            while (entrys.hasMoreElements()) {
                ZipEntry entry = entrys.nextElement();
                String name = entry.getName();
                if (!name.startsWith(subDir)) {
                    continue;
                }
                //subDir
                name = name.replace(subDir, "").trim();
                if (name.length() < 2) {
                    log.debug(name + "  < 2");
                    continue;
                }
                if (entry.isDirectory()) {
                    File dir = new File(base, name);
                    if (!dir.exists()) {
                        dir.mkdirs();
                        log.debug("create directory");
                    } else {
                        log.debug("the directory is existing.");
                    }
                    log.debug(name + " is a directory");
                } else {
                    File file = new File(base, name);
                    if (file.exists() && force) {
                        file.delete();
                    }
                    if (!file.exists()) {
                        InputStream in = zip.getInputStream(entry);
                        FileUtils.copyInputStreamToFile(in, file);
                        log.debug("create file.");
                        in.close();
                    } else {
                        log.debug("the file is existing");
                    }
                    log.debug(name + " is not a directory");
                }
            }
            zip.close();
        } catch (ZipException ex) {
            ex.printStackTrace();
            log.error("file unzip failed.", ex);
            return false;
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error("file IO failed", ex);
            return false;
        }
        return true;
    }

    /**
     * ZIP
     *
     * @param sourcePath 
     * @param zipPath ?zip??
     */
    public static void createZip(String sourcePath, String zipPath) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);
            writeZip(new File(sourcePath), "", zos);
        } catch (FileNotFoundException e) {
            log.error("create zip file failed.", e);
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("create zip file failed.", e);
            }

        }
    }

    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.exists()) {
            if (file.isDirectory()) {//?
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                for (File f : files) {
                    writeZip(f, parentPath, zos);
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }

                } catch (FileNotFoundException e) {
                    log.error("create zip file failed.", e);
                } catch (IOException e) {
                    log.error("create zip file failed.", e);
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        log.error("create zip file failed.", e);
                    }
                }
            }
        }
    }

    /**
     * ??.
     *
     * @param baseDir 
     * @param absFileName ???ZipEntryname
     * @return java.io.File 
     */
    private static File getRealFileName(String baseDir, String absFileName) {
        String[] dirs = absFileName.split("/");
        //System.out.println(dirs.length);
        File ret = new File(baseDir);
        //System.out.println(ret);
        if (dirs.length > 1) {
            for (int i = 0; i < dirs.length - 1; i++) {
                ret = new File(ret, dirs[i]);
            }
        }
        if (!ret.exists()) {
            ret.mkdirs();
        }
        ret = new File(ret, dirs[dirs.length - 1]);
        return ret;
    }

    public static void main(String[] args) {

    }
}