集册 Java实例教程 将ZIP归档文件提取到目标目录

将ZIP归档文件提取到目标目录

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

434
将ZIP归档文件提取到目标目录
//时代Java - nowjava.com


//package com.nowjava;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.file.Path;


import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;


public class Main {

    protected static final int bufferSize = 1024;


    /**

     * Extracts a ZIP archive into the target directory

     * 

     * @param archive            Path to the archive to extract

     * @param targetDirectory      Directory to which the files will be extracted

     * @throws Exception

     */

    public static synchronized void extract(Path archive,
    /*
    来 自*
     时 代 J a v a - N o w J a v a . c o m
    */

            Path targetDirectory) throws Exception {

        System.out.println("Unzipping " + archive.getFileName().toString()

                + "...");

        byte[] buffer = new byte[bufferSize];


        // extracts the source code archive to the target directory

        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(

                archive.toFile()))) {

            ZipEntry ze;

            while ((ze = zin.getNextEntry()) != null) {

                Path extractedFile = targetDirectory.resolve(ze.getName());

                try (FileOutputStream fout = new FileOutputStream(

                        extractedFile.toFile())) {


                    int len;

                    while ((len = zin.read(buffer)) > 0) {

                        fout.write(buffer, 0, len);

                    }


                    zin.closeEntry();

                } catch (IOException ioe_inner) {

                    throw new Exception(

                            "Error while extracting a file from the archive: "
展开阅读全文