package cn.ysk.cashier.utils;

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工具类
 *
 * @author GYJ
 */
public class ZipUtils {
    public static void zipDirectory(File directoryToZip, File zipFile) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        compressDirectoryToZipfile(directoryToZip, directoryToZip, zos);
        zos.close();
        fos.close();
    }

    private static void compressDirectoryToZipfile(File rootDir, File currentDir, ZipOutputStream zos) throws IOException {
        File[] files = currentDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    compressDirectoryToZipfile(rootDir, file, zos);
                } else {
                    ZipEntry zipEntry = new ZipEntry(rootDir.toURI().relativize(file.toURI()).getPath());
                    zos.putNextEntry(zipEntry);
                    FileInputStream fis = new FileInputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                    fis.close();
                    zos.closeEntry();
                }
            }
        }
    }

}
