package com.ywt.mg.core.utils;


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

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;


/**
 * @author daiyihua
 * @create 2020-11-24 11:15
 * @program bank_service
 * @description Zip文件处理工具类
 **/
public class FileUtil {


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

    /**
     * 删除指定文件夹下文件
     *
     * @param filePath
     */
    public static void deleteFolders(String filePath) {
        Path path = Paths.get(filePath);
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                    Files.delete(file);
                    LOGGER.info("删除文件: {}", file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                                                          IOException exc) throws IOException {
                    Files.delete(dir);
                    LOGGER.info("文件夹被删除: {}", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件路径
     */
    public void deleteFile(String fileName) {
        try {
            //创建一个文件对象
            File file = new File(fileName);
            // 删除文件
            boolean value = file.delete();
            if (value) {
                LOGGER.info(fileName + "已成功删除.");
            } else {
                LOGGER.info(fileName + "文件不存在");
            }
        } catch (Exception e) {
            LOGGER.error("delete file error:{}", e, e.getMessage());
        }
    }

    /**
     * 判断是否存在文件夹，如果不存在，那就创建
     *
     * @param filePath 文件路径
     */
    public static void createFoldersIfNotExit(String filePath) {
        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
        } catch (Exception e) {
            LOGGER.error("FileUtil#createFoldersIfNotExit error:{}", e, e.getMessage());
        }
    }
}
