java:Zip压缩工具类

文章提供了两个Java实现Zip压缩和解压缩的工具类,一个是基于ApacheAnt库,另一个是使用JDK内置API。Ant工具类能正确处理文件名中的中文,而JDK工具类在处理中文时可能出现乱码问题。这两个工具类都包括对文件和目录的递归压缩与解压缩功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 基于Ant的Zip压缩工具类

1.1 pom.xml引入依赖包

        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.10.13</version>
        </dependency>

1.2 工具类

package com.example.demo.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;


public class AntZipUtils {

    public static final String ENCODING_DEFAULT = "UTF-8";

    public static final int BUFFER_SIZE_DIFAULT = 128;

    public static void makeZip(String[] inFilePaths, String zipPath)
            throws Exception {
        makeZip(inFilePaths, zipPath, ENCODING_DEFAULT);
    }

    public static void makeZip(String[] inFilePaths, String zipPath,
                               String encoding) throws Exception {
        File[] inFiles = new File[inFilePaths.length];
        for (int i = 0; i < inFilePaths.length; i++) {
            inFiles[i] = new File(inFilePaths[i]);
        }
        makeZip(inFiles, zipPath, encoding);
    }

    public static void makeZip(File[] inFiles, String zipPath) throws Exception {
        makeZip(inFiles, zipPath, ENCODING_DEFAULT);
    }

    public static void makeZip(File[] inFiles, String zipPath, String encoding)
            throws Exception {
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(zipPath)));
        zipOut.setEncoding(encoding);
        for (int i = 0; i < inFiles.length; i++) {
            File file = inFiles[i];
            doZipFile(zipOut, file, file.getParent());
        }
        zipOut.flush();
        zipOut.close();
    }

    private static void doZipFile(ZipOutputStream zipOut, File file,
                                  String dirPath) throws FileNotFoundException, IOException {
        if (file.isFile()) {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            String zipName = file.getPath().substring(dirPath.length());
            while (zipName.charAt(0) == '\\' || zipName.charAt(0) == '/') {
                zipName = zipName.substring(1);
            }
            ZipEntry entry = new ZipEntry(zipName);
            zipOut.putNextEntry(entry);
            byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
            int size;
            while ((size = bis.read(buff, 0, buff.length)) != -1) {
                zipOut.write(buff, 0, size);
            }
            zipOut.closeEntry();
            bis.close();
        } else {
            File[] subFiles = file.listFiles();
            for (File subFile : subFiles) {
                doZipFile(zipOut, subFile, dirPath);
            }
        }
    }

    public static void unZip(String zipFilePath, String storePath)
            throws IOException {
        unZip(new File(zipFilePath), storePath);
    }

    public static void unZip(File zipFile, String storePath) throws IOException {
        if (new File(storePath).exists()) {
            new File(storePath).delete();
        }
        new File(storePath).mkdirs();

        ZipFile zip = new ZipFile(zipFile);
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip
                .getEntries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (zipEntry.isDirectory()) {
                // TODO
            } else {
                String zipEntryName = zipEntry.getName();
                if (zipEntryName.indexOf(File.separator) > 0) {
                    String zipEntryDir = zipEntryName.substring(0, zipEntryName
                            .lastIndexOf(File.separator) + 1);
                    String unzipFileDir = storePath + File.separator
                            + zipEntryDir;
                    File unzipFileDirFile = new File(unzipFileDir);
                    if (!unzipFileDirFile.exists()) {
                        unzipFileDirFile.mkdirs();
                    }
                }

                InputStream is = zip.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(new File(storePath
                        + File.separator + zipEntryName));
                byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
                int size;
                while ((size = is.read(buff)) > 0) {
                    fos.write(buff, 0, size);
                }
                fos.flush();
                fos.close();
                is.close();
            }
        }
    }

}

1.3 测试工具类

    public static void main(String[] args) throws Exception {
        String rootDir = "D:\\handsome";
        String zipPath = "D:\\ZipDemo.zip";
        AntZipUtils.makeZip(new String[] { rootDir }, zipPath);
        AntZipUtils.unZip(zipPath, "D:\\handsome_zip");
    }

2 基于JDK的Zip压缩工具类

该版本存在问题:压缩时如果目录或文件名含有中文,压缩后会变成乱码

package com.example.demo.Utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


public class JdkZipUtils {

    public static final int BUFFER_SIZE_DIFAULT = 128;

    public static void makeZip(String[] inFilePaths, String zipFilePath)
            throws Exception {
        File[] inFiles = new File[inFilePaths.length];
        for (int i = 0; i < inFilePaths.length; i++) {
            inFiles[i] = new File(inFilePaths[i]);
        }
        makeZip(inFiles, zipFilePath);
    }

    public static void makeZip(File[] inFiles, String zipFilePath)
            throws Exception {
        ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(zipFilePath)));
        for (int i = 0; i < inFiles.length; i++) {
            doZipFile(zipOut, inFiles[i], inFiles[i].getParent());
        }
        zipOut.flush();
        zipOut.close();
    }

    private static void doZipFile(ZipOutputStream zipOut, File file,
                                  String dirPath) throws FileNotFoundException, IOException {
        if (file.isFile()) {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            String zipName = file.getPath().substring(dirPath.length());
            while (zipName.charAt(0) == '\\' || zipName.charAt(0) == '/') {
                zipName = zipName.substring(1);
            }
            ZipEntry entry = new ZipEntry(zipName);
            zipOut.putNextEntry(entry);
            byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
            int size;
            while ((size = bis.read(buff, 0, buff.length)) != -1) {
                zipOut.write(buff, 0, size);
            }
            zipOut.closeEntry();
            bis.close();
        } else {
            File[] subFiles = file.listFiles();
            for (File subFile : subFiles) {
                doZipFile(zipOut, subFile, dirPath);
            }
        }
    }

    public static void unZip(String zipFilePath, String storePath)
            throws IOException {
        unZip(new File(zipFilePath), storePath);
    }

    public static void unZip(File zipFile, String storePath) throws IOException {
        if (new File(storePath).exists()) {
            new File(storePath).delete();
        }
        new File(storePath).mkdirs();

        ZipFile zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();

            if (zipEntry.isDirectory()) {
                // TODO
            } else {
                String zipEntryName = zipEntry.getName();
                if (zipEntryName.indexOf(File.separator) > 0) {
                    String zipEntryDir = zipEntryName.substring(0, zipEntryName
                            .lastIndexOf(File.separator) + 1);
                    String unzipFileDir = storePath + File.separator
                            + zipEntryDir;
                    File unzipFileDirFile = new File(unzipFileDir);
                    if (!unzipFileDirFile.exists()) {
                        unzipFileDirFile.mkdirs();
                    }
                }

                InputStream is = zip.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(new File(storePath
                        + File.separator + zipEntryName));
                byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
                int size;
                while ((size = is.read(buff)) > 0) {
                    fos.write(buff, 0, size);
                }
                fos.flush();
                fos.close();
                is.close();
            }
        }
    }

}

测试工具类

    public static void main(String[] args) throws Exception {
        String rootDir = "D:\\handsome";
        File[] inFiles = new File(rootDir).listFiles();
        String zipPath = "D:\\ZipDemo.zip";

        JdkZipUtils.makeZip(inFiles, zipPath);

        JdkZipUtils.unZip(zipPath, "D:\\handsome_zip");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不死鸟.亚历山大.狼崽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值