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();
        }
    }
}
