JAVA 使用Channel将文件夹压缩成ZIP

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: 压缩工具类
 * @author: wujie
 * @create: 2020-08-28 09:49
 **/
@Slf4j
public class ZipUtils {

    /**
     * 文件夹压缩成zip
     *
     * @param zipFilePath
     * @param filePath
     */
    public static void zipFileChannel(String zipFilePath, String filePath) {
        long beginTime = System.currentTimeMillis();
        File zipFile = new File(zipFilePath);
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
             WritableByteChannel writableByteChannel = Channels.newChannel(zipOut)) {
            File path = new File(filePath);
            File[] files = path.listFiles();
            FileChannel fileChannel;
            for (File file : files) {
                fileChannel = new FileInputStream(file).getChannel();
                zipOut.putNextEntry(new ZipEntry(file.getName()));
                fileChannel.transferTo(0, file.length(), writableByteChannel);
            }
            long endTime = System.currentTimeMillis();
            log.info("File compression complete. Time consuming: {}ms. File size:{}", endTime - beginTime, CommonUtils.formatBytes(zipFile.length()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        zipFileChannel("D:\\Downloads\\tempFile\\a.zip", "D:\\Downloads\\tempFile\\test");
    }
}
/**
     * 字节转换,计算文件大小
     *
     * @param size
     * @return
     */
    public static String formatBytes(long size) {
        int GB = 1024 * 1024 * 1024;
        int MB = 1024 * 1024;
        int KB = 1024;
        DecimalFormat df = new DecimalFormat("0.00");
        String resultSize = "";
        if (size / GB >= 1) {
            resultSize = df.format(size / (float) GB) + "GB";
        } else if (size / MB >= 1) {
            resultSize = df.format(size / (float) MB) + "MB";
        } else if (size / KB >= 1) {
            resultSize = df.format(size / (float) KB) + "KB";
        } else {
            resultSize = size + "B";
        }
        return resultSize;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值