package com.simuwang.base.common.util;

import jakarta.mail.Part;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static void writeFile(String fileName, String content) {
        writeFile(new File(fileName), content, "UTF-8");
    }

    public static void writeFile(File file, String content, String charsets) {
        writeFile(file, content, charsets, false);
    }

    public static void writeFile(File file, String content, String charsets, boolean append) {
        Writer fw = null;
        String fileName = file.getAbsolutePath();

        try {
            File folder = file.getParentFile();
            if (!folder.exists()) {
                folder.setExecutable(true, false);
                folder.setReadable(true, false);
                folder.mkdirs();
            }

            if (append) {
                fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), charsets));
            } else {
                fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsets));
            }

            fw.write(content);
            fw.flush();
        } catch (IOException var15) {
            logger.error("写入失败！file=" + fileName);
            var15.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException var14) {
                logger.error("写入的IO关闭失败！file= " + fileName);
                var14.printStackTrace();
            }

        }
    }

    public static void saveFile(File saveFile, Part part) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );
        byte[] buff = new byte[2048];
        InputStream is = part.getInputStream();
        int ret = 0;
        while( (ret = is.read(buff)) > 0 ){
            bos.write(buff, 0, ret);
        }
        bos.close();
        is.close();
    }
}
