Java-解压缩zip

Java-解压缩zip

Tags: Java

摘要

Java-解压缩zip

Java解压缩zip文件

上一节,学习了如何把文件压缩到zip文件中,这节展示如何解压zip

使用ZipInputStream读取zip文件
获取ZipEntry对象,然后写出到FileOutputStram

解压zip文件例子

package cn.javacore.io.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class _03_UnZip {
    List<String> fileList;
    private static final String INPUT_ZIP_FILE = "/home/zhu/javacore.cn/MyFile.zip";
    private static final String OUTPUT_FOLDER = "/home/zhu/javacore.cn/outputzip";

    public static void main(String[] args) {
        _03_UnZip unZip = new _03_UnZip();
        unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
    }

    /**
     * Unzip it
     *
     * @param zipFile      input zip file
     * @param outputFolder zip file output folder
     */
    public void unZipIt(String zipFile, String outputFolder) {

        byte[] buffer = new byte[1024];

        try {

            //create output directory is not exists
            File folder = new File(OUTPUT_FOLDER);
            if (!folder.exists()) {
                folder.mkdir();
            }

            //get the zip file content
            ZipInputStream zis =
                    new ZipInputStream(new FileInputStream(zipFile));
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                File newFile = new File(outputFolder + File.separator + fileName);
                System.out.println("file unzip : " + newFile.getAbsoluteFile());
                //create all non exists folders
                //else you will hit FileNotFoundException for compressed folder
                new File(newFile.getParent()).mkdirs();
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
            System.out.println("Done");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

解压zip,输出结果

file unzip : /home/zhu/javacore.cn/outputzip/test-02.log
file unzip : /home/zhu/javacore.cn/outputzip/test.log
file unzip : /home/zhu/javacore.cn/outputzip/sub/ABC-02.log
file unzip : /home/zhu/javacore.cn/outputzip/sub/abc.log
Done