集册 Java实例教程 将文件解压缩到指定目录

将文件解压缩到指定目录

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

409
将文件解压缩到指定目录
/*
n o w    j a v a  . c o m 提 供
*/

/**

 * e-Science Central

 * Copyright (C) 2008-2013 School of Computing Science, Newcastle University

 *

 * This program is free software; you can redistribute it and/or

 * modify it under the terms of the GNU General Public License

 * version 2 as published by the Free Software Foundation at:

 * http://www.gnu.org/licenses/gpl-2.0.html

 *

 * This program is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 * GNU General Public License for more details.

 *

 * You should have received a copy of the GNU General Public License

 * along with this program; if not, write to the Free Software

 * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA.

 */

//package com.nowjava;

import java.io.*;

import java.util.zip.*;

import java.util.*;


public class Main {

    /** Unzip a file to a specified directory */

    public static void unzip(File file, File targetDirectory)

            throws Exception {

        Enumeration<? extends ZipEntry> entries;

        ZipFile zipFile = new ZipFile(file);

        try {

            File extractFile;


            entries = zipFile.entries();


            while (entries.hasMoreElements()) {

                ZipEntry entry = entries.nextElement();


                if (!entry.getName().startsWith(".")) {//n o w    j a v a  . c o m 提 供

                    if (entry.isDirectory()) {

                        // Assume directories are stored parents first then children.

                        (new File(targetDirectory, entry.getName()))

                                .mkdirs();

                        continue;

                    }


                    InputStream inStream = zipFile.getInputStream(entry);

                    BufferedOutputStream outStream = null;

                    try {

                        extractFile = new File(targetDirectory,

                                entry.getName());

                        if (extractFile.getParentFile() != null

                                && !extractFile.getParentFile().exists()) {

                            extractFile.getParentFile().mkdirs();

                        }


                        outStream = new BufferedOutputStream(

                                new FileOutputStream(extractFile));

                        copyInputStream(inStream, outStream);

                    } finally {

                        inStream.close();

                        if (outStream != null) {

                            outStream.close();

                        }

                    }

                }

            }

        } finally {

            zipFile.close();

        }

    }


    
展开阅读全文