ZipFileUtil.java 2.07 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
package mobvista.dmp.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @package: mobvista.dmp.util
 * @author: wangjf
 * @date: 2021/8/3
 * @time: 11:21 上午
 * @email: jinfeng.wang@mobvista.com
 */
public class ZipFileUtil {

    public static final Logger logger = LoggerFactory.getLogger(ZipFileUtil.class);

    /**
     * 压缩单个文件
     */
    public static void zipFile(String filePath, String zipPath) {
        try {
            File file = new File(filePath);
            File zipFile = new File(zipPath);
            InputStream input = new FileInputStream(file);
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.putNextEntry(new ZipEntry(file.getName()));
            int temp = 0;
            while ((temp = input.read()) != -1) {
                zipOut.write(temp);
            }
            input.close();
            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void compress(String filePath, String gzipPath) {
        byte[] buffer = new byte[1024];
        try {
            //  Specify Name and Path of Output GZip file here
            GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream(gzipPath));
            //  Specify the input file here
            FileInputStream fis = new FileInputStream(filePath);
            //  Read from input file and write to output GZip file
            int length;
            //  fis.read(buffer), 结果时Buffer有了内容,同时返回读取内容的长度,读到文件末尾时读取内容的长度变为-1
            while ((length = fis.read(buffer)) > 0) {
                gos.write(buffer, 0, length);
            }
            fis.close();
            gos.finish();
            gos.close();
            System.out.println(filePath + ",File Compressed!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}