集册 Java实例教程 将Zip文件解压缩到目录,可以选择删除该Zip文件。

将Zip文件解压缩到目录,可以选择删除该Zip文件。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

566
将Zip文件解压缩到目录,可以选择删除该Zip文件。
// 来自 N o w J a v a . c o m


import java.io.*;

import java.util.zip.*;

import java.lang.RuntimeException;


public class Main{

    private static int BUFFER_SIZE = 2048;

    /**

     * Decompress Zip file to a directory, optionally deleting the zip file.

     *

     * Oracle "recipe" with a touch of existing file/directory handling

     *

     * @see:

     * http://www.oracle.com/technetwork/articles/java/compress-1565076.html

     * http://android-er.blogspot.com.es/2011/04/unzip-compressed-file-using-javautilzip.html

     */

    public static void decompressZip(String zipFile, String destDir,

            boolean deleteZip) throws RuntimeException {

        Logger.coloredLog("\nDecompressing " + zipFile + " to " + destDir

                + "\n", Logger.ANSI_YELLOW);


        // make sure destination directory ends with "/" for later concating

        if (!destDir.endsWith("/"))

            destDir = destDir.concat("/");


        try {
        /**
         from
        * nowjava.com - 时代Java 
        **/

            BufferedOutputStream bos = null;

            FileInputStream fis = new FileInputStream(zipFile);

            ZipInputStream zis = new ZipInputStream(

                    new BufferedInputStream(fis));

            ZipEntry zipEntry;


            // read all entries (files/directories) from zip file

            while ((zipEntry = zis.getNextEntry()) != null) {

                String zipEntryName = zipEntry.getName();

                File file = new File(destDir + zipEntryName);


                // if file already exists...

                if (file.exists()) {

                    // ...do nothing

                    Logger.coloredLog("Skipping: " + zipEntry

                            + ", already exists", Logger.ANSI_CYAN);

                } else {

                    // if file is a directory...

                    if (zipEntry.isDirectory()) {

                        // ...create it

                        file.mkdirs();

                    } else {

                        // file IS a file, extract...

                        Logger.log("Extracting: " + zipEntry);


                        byte data[] = new byte[BUFFER_SIZE];

                        FileOutputStream fos = new FileOutputStream(file);

                        bos = new BufferedOutputStream(fos, BUFFER_SIZE);

                        int count;


                        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {

                            bos.write(data, 0, count);

                        }


                        bos.flush();

                        bos.close();

                    }

                }

            }

展开阅读全文