将指定文件压缩成zip包

时间:2022-12-29 11:34:02
package com.csf.executor.word.common;

import org.apache.commons.lang.StringUtils;

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;

/**
 * 将指定文件压缩成zip包
 */
public class CommonZipUtil {
    public static void packageZip(String srcFile, String destFile) throws IOException {
        if (StringUtils.isBlank(srcFile) || StringUtils.isBlank(destFile)) {
            return;
        }
        File f = new File(srcFile);
        try (
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));
                FileInputStream in = new FileInputStream(srcFile);
        ) {
            out.putNextEntry(new ZipEntry(f.getName()));
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            out.flush();
        }

    }

    public static void main(String[] args) throws IOException {
        packageZip("E:\\临时\\excel\\2018-03-26-5.xlsx", "E:\\临时\\excel\\2018-03-26-5.zip");
    }

}