100个Java工具类之23:文件的压缩与解压缩

本文介绍了在Java中使用ZipOutputStream和GZIPOutputStream进行文件压缩的方法,以及通过测试显示的压缩与解压性能。压缩200MB文件约需8秒,大小减至150MB;解压同样快速,仅1秒。

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

文件压缩,指将一个大文件或目录压缩为单个压缩文件。好处是减少磁盘空间更少的,提高文件传输效率。
Java中提供了ZipOutputStream和GZIPOutputStream类供文件压缩使用。
通过测试,本工具类压缩200MB文件,用时8s,压缩后文件大小为150mb,无论从效率上还是从效果上讲,都是可圈可点的。

一、压缩成zip文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.logging.log4j.util.Strings;
/**
     * @param srcDir 压缩文件夹路径
     * @param targetDir    压缩后文件的路径名称
     * @param KeepDirStructure  是否保留原来的目录结构
     * @throws RuntimeException
     */
    public static void toZip(String srcDir, String targetDir, boolean KeepDirStructure) throws RuntimeException {
        File sourceFile = new File(srcDir);
        String sourcePath = sourceFile.getParentFile().toString();
        String fileName = sourceFile.getName();
        ZipOutputStream zos = null;
        try {
            FileOutputStream out = null;
            if (Strings.isEmpty(targetDir)) {
                if (sourceFile.isDirectory()) {
                    out = new FileOutputStream(new File(sourcePath + "/" + fileName + ".zip"));
                } else {
                    out = new FileOutputStream(new File(sourcePath + "/" + fileName.substring(0, fileName.lastIndexOf('.')) + ".zip"));
                }
            } else {
                out = new FileOutputStream(new File(targetDir));
            }
            zos = new ZipOutputStream(out);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("压缩失败!", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean isDir) throws Exception {
        byte[] buf = new byte[2 * 1024];
        if (sourceFile.isFile()) {
            zos.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                if (isDir) {
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    if (isDir) {
                        compress(file, zos, name + "/" + file.getName(), isDir);
                    } else {
                        compress(file, zos, file.getName(), isDir);
                    }
                }
            }
        }
    }

二、文件解压

通过测试,本工具类解压200MB文件,用时1s,大大超出了笔者的想象。

/**
     * 解压zip文件
     *
     * @param srcFile 待解压的zip文件
     * @param descDir 解压后的存放路径
     * @throws IOException
     **/
    public static void unZipFiles(String srcFile, String descDir) throws IOException {

        File descDirFile = new File(descDir);
        if (!descDirFile.exists()) {
            descDirFile.mkdirs();
        }
        ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));
        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            if (new File(outPath).isDirectory()) {
                continue;
            }
            try(InputStream in =zip.getInputStream(entry);
                OutputStream out =new FileOutputStream(outPath)){
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
            }catch(IOException e){
                log.error(e.getMessage(),e);
            }
        }
        zipFile.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值