package com.jeeplus.assess.invoice.utils.OMS;

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;

/**
 * 文件管理
 * @author: 徐滕
 * @version: 2023-12-29 09:54
 */
public class FileUtil {

    /**
     * 文件压缩
     * @param sourceFolder
     * @param zipFile
     */
    public static void zipFolder(String sourceFolder, String zipFile) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            File folder = new File(sourceFolder);
            addFolderToZip("", folder, zos);

            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void addFolderToZip(String parentFolder, File folder, ZipOutputStream zos) throws IOException {
        for (String fileName : folder.list()) {
            if (parentFolder.equals("")) {
                addFileToZip(folder.getName(), new File(folder, fileName), zos);
            } else {
                addFileToZip(parentFolder + "/" + folder.getName(), new File(folder, fileName), zos);
            }
        }
    }

    public static void addFileToZip(String path, File file, ZipOutputStream zos) throws IOException {
        if (file.isDirectory()) {
            addFolderToZip(path, file, zos);
        } else {
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(file);
            zos.putNextEntry(new ZipEntry(path + "/" + file.getName()));
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
            fis.close();
        }
    }

}
