package cn.com.qmth.examcloud.core.questions.base;

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

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

public class ZipUtils {
    private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);

    public static void doCompress(String srcFile, String zipFile) {
        doCompress(new File(srcFile), new File(zipFile));
    }

    /**
     * 文件压缩
     *
     * @param srcFile  目录或者单个文件
     * @param destFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File destFile) {
        try (FileOutputStream fos = new FileOutputStream(destFile);
             ZipOutputStream out = new ZipOutputStream(fos);) {

            if (srcFile.isDirectory()) {
                File[] files = srcFile.listFiles();
                for (File file : files) {
                    doCompress(file, out);
                }
            } else {
                doCompress(srcFile, out);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void doCompress(String pathname, ZipOutputStream out) {
        doCompress(new File(pathname), out);
    }

    public static void doCompress(File file, ZipOutputStream out) {
        if (!file.exists()) {
            return;
        }

        try (FileInputStream fis = new FileInputStream(file);) {
            ZipEntry entry = new ZipEntry(file.getName());
            out.putNextEntry(entry);

            byte[] buffer = new byte[1024];
            int len;
            // 读取文件的内容,打包到zip文件
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                out.closeEntry();
            } catch (IOException e) {
                //ignore
            }
        }
    }

}