【Java】ZIP解压与压缩

by img Microanswer 创建时间:May 4, 2020 10:45:04 AM 

标签: zip 解压 压缩 java 打包



有时候我们在Java程序里面难免会遇到处理zip文件的需求,要么是解压某个文件,要么是压缩一堆文件,为了快速处实现这个需求功能,特记录自己写的一个工具类在这里。仅供参考。

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 压缩文件工工具
 */
public class ZipTool {

    /**
     * 解压zip
     *
     * @param srcZip
     * @param targetDir
     * @return
     */
    public static boolean unZipFile(File srcZip, File targetDir) throws Exception {
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        FileInputStream fileInputStream = new FileInputStream(srcZip);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

        ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream);

        ZipEntry nextEntry = null;

        while ((nextEntry = zipInputStream.getNextEntry()) != null) {
            if (nextEntry.isDirectory()) {
                File dir = new File(targetDir, nextEntry.getName());
                dir.mkdirs();
            } else {
                File file = new File(targetDir.getCanonicalPath() + "/" + nextEntry.getName());

                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

                byte cache[] = new byte[4096];
                int ccacheSize = 0;
                while ((ccacheSize = zipInputStream.read(cache)) != -1) {
                    bufferedOutputStream.write(cache, 0, ccacheSize);
                }
                bufferedOutputStream.flush();
                fileOutputStream.flush();
                fileOutputStream.close();
                bufferedOutputStream.close();
            }
        }
        zipInputStream.close();
        return true;
    }

    /**
     * 压缩文件
     *
     * @param files    要压缩的文件
     * @param zipFile_ 目标压缩文件,就是files文件压缩成功后生成的zip文件路径。(存在则覆盖)
     */
    public static boolean zipFile(ArrayList<File> files, File zipFile_) throws Exception {

        if (files == null || files.size() <= 0) {
            return false;
        }
        File p = zipFile_.getParentFile();
        if (!p.exists()) {
            p.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(zipFile_);
        ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
        boolean s = zipFile(files, zipOutputStream, "", zipFile_);
        zipOutputStream.finish();
        fileOutputStream.flush();
        zipOutputStream.close();
        fileOutputStream.close();
        return s;
    }

    private static boolean zipFile(ArrayList<File> files, ZipOutputStream zipOutputStream, String path, final File zipFile_) throws Exception {
        String pathTemp;
        for (File file : files) {
            ZipEntry zipEntry;
            if (file.isDirectory()) {
                pathTemp = file.getName() + "/";
                zipEntry = new ZipEntry(path + pathTemp);
            } else {
                pathTemp = file.getName();
                zipEntry = new ZipEntry(path + pathTemp);
            }
            zipOutputStream.putNextEntry(zipEntry);
            if (file.isDirectory()) {
                File[] files1 = file.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File fileIn) {
                        try {
                            String filterfilePath = fileIn.getCanonicalPath();
                            String zipFile_Path = zipFile_.getCanonicalPath();
                            if (zipFile_Path.equals(filterfilePath)) {
                                return false;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return true;
                    }
                });
                if (files1 != null && files1.length > 0) {
                    ArrayList<File> fs = new ArrayList<>();
                    Collections.addAll(fs, files1);
                    zipFile(fs, zipOutputStream, path + pathTemp, zipFile_);
                }
            } else {
                FileInputStream fileInputStream = new FileInputStream(file);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

                byte[] cache = new byte[4096];
                int cacheSize = 0;

                while ((cacheSize = bufferedInputStream.read(cache)) != -1) {
                    zipOutputStream.write(cache, 0, cacheSize);
                }
                bufferedInputStream.close();
                fileInputStream.close();
            }
        }
        return true;
    }

    // 测试
    public static void main(String args[]) throws Exception {
        System.out.println("开始压缩文件....");

        // 加入要压缩的文件
        ArrayList<File> files = new ArrayList<>();
        files.add(new File("D:\\project\\static"));
        files.add(new File("D:\\project\\index.html"));
        files.add(new File("D:\\project\\index2.html"));
        files.add(new File("D:\\project\\index3.html"));

        // 压缩后生成的文件
        File zip = new File("D:\\html.zip");
        zipFile(files, zip);
        System.out.println("压缩成功");

        int time = 3;
        while (time > 0) {
            System.out.printf("将在%d秒后进行解压\n", time);
            Thread.sleep(1000);
            time --;
        }
        System.out.println("开始解压...");
        unZipFile(zip, new File("D:\\html\\"));
        System.out.println("解压成功");
    }
}
全文完, 转载请注明出处。 对你有帮助?不如赞一个吧:
发表评论(发表评论需要登录,你现在还没有登录。)
你需要先登录才可以评论。

评论列表 (0条)