com.alibaba.antx.util.ZipUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.alibaba.antx.util.ZipUtil.java

Source

/*
 * Copyright (c) 2002-2012 Alibaba Group Holding Limited.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.antx.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Zip
 *
 * @author Michael Zhou
 */
public class ZipUtil {
    private static final Log log = LogFactory.getLog(ZipUtil.class);

    /**
     * ?jar URL
     *
     * @param jarfileURL jarURL
     * @param path       ?jar
     * @return jar URL
     */
    public static URL getJarURL(URL jarfileURL, String path) throws MalformedURLException {
        StringBuffer url = new StringBuffer();

        url.append("jar:").append(jarfileURL.toExternalForm()).append("!");

        if (!path.startsWith("/")) {
            url.append("/");
        }

        url.append(path.replace('\\', '/'));

        return new URL(url.toString());
    }

    /**
     * ??zip???
     *
     * @param zipfileURL zipURL
     * @param includes   ?
     * @param excludes   ??
     * @return URL
     */
    public static URL[] getFilesInZipFile(URL zipfileURL, String[] includes, String[] excludes) throws IOException {
        String[] filenames = getFileNamesInZipFile(zipfileURL, includes, excludes);
        URL[] urls = new URL[filenames.length];

        for (int i = 0; i < filenames.length; i++) {
            urls[i] = getJarURL(zipfileURL, filenames[i]);
        }

        return urls;
    }

    /**
     * ??zip???
     *
     * @param zipfileURL zipURL
     * @param includes   ?
     * @param excludes   ??
     * @return 
     */
    public static String[] getFileNamesInZipFile(URL zipfileURL, String[] includes, String[] excludes)
            throws IOException {
        ZipScanner zipScanner = new ZipScanner();

        zipScanner.setSrc(zipfileURL);
        zipScanner.setIncludes(includes);
        zipScanner.setExcludes(excludes);
        zipScanner.addDefaultExcludes();
        zipScanner.scan();

        return zipScanner.getIncludedFiles();
    }

    /**
     * zip
     *
     * @param zipfile   Zip
     * @param todir     
     * @param overwrite ?
     * @throws IOException Zip?
     */
    public static void expandFile(File zipfile, File todir, boolean overwrite) throws IOException {
        InputStream istream = null;

        try {
            istream = new FileInputStream(zipfile);
            expandFile(istream, todir, overwrite);
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * zip
     *
     * @param istream   ?
     * @param todir     
     * @param overwrite ?
     * @throws IOException Zip?
     */
    public static void expandFile(InputStream istream, File todir, boolean overwrite) throws IOException {
        ZipInputStream zipStream = null;

        if (!(istream instanceof BufferedInputStream)) {
            istream = new BufferedInputStream(istream, 8192);
        }

        try {
            zipStream = new ZipInputStream(istream);

            ZipEntry zipEntry = null;

            while ((zipEntry = zipStream.getNextEntry()) != null) {
                extractFile(todir, zipStream, zipEntry, overwrite);
            }

            log.info("expand complete");
        } finally {
            if (zipStream != null) {
                try {
                    zipStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 
     *
     * @param todir     
     * @param zipStream ?
     * @param zipEntry  zip
     * @param overwrite ?
     * @throws IOException Zip?
     */
    protected static void extractFile(File todir, InputStream zipStream, ZipEntry zipEntry, boolean overwrite)
            throws IOException {
        String entryName = zipEntry.getName();
        Date entryDate = new Date(zipEntry.getTime());
        boolean isDirectory = zipEntry.isDirectory();
        File targetFile = FileUtil.getFile(todir, entryName);

        if (!overwrite && targetFile.exists() && targetFile.lastModified() >= entryDate.getTime()) {
            log.debug("Skipping " + targetFile + " as it is up-to-date");
            return;
        }

        log.info("expanding " + entryName + " to " + targetFile);

        if (isDirectory) {
            targetFile.mkdirs();
        } else {
            File dir = targetFile.getParentFile();

            dir.mkdirs();

            byte[] buffer = new byte[8192];
            int length = 0;
            OutputStream ostream = null;

            try {
                ostream = new BufferedOutputStream(new FileOutputStream(targetFile), 8192);

                while ((length = zipStream.read(buffer)) >= 0) {
                    ostream.write(buffer, 0, length);
                }
            } finally {
                if (ostream != null) {
                    try {
                        ostream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        targetFile.setLastModified(entryDate.getTime());
    }
}