package com.sheep.jiuyan.samllsheep.utils;


import android.support.annotation.NonNull;

import com.sheep.gamegroup.util.LogUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * Created by realicing on 2018/6/1.
 */

public class FileUtil {


    public static void deleteFile(File file) {
        deleteFile(file, true);
    }
    public static void deleteFile(File file, boolean isDeleteDir) {
        if (file != null && file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File[] files = file.listFiles(); // 声明目录下所有的文件 files[];
                if(files != null) {
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                    }
                }
                if(isDeleteDir)
                    file.delete();
            }
        }
    }

    public static void copyFile(@NonNull File fileFrom, @NonNull File dirTo) throws IOException {
        LogUtil.println("copyFile", fileFrom.getAbsolutePath(), dirTo.getAbsolutePath());
        if(!dirTo.isDirectory()){
            return;
        }
        if(!dirTo.exists())
            dirTo.mkdirs();
        File dest= new File(dirTo, fileFrom.getName());
        if (dest.exists()) {
            if(dest.delete()){
                LogUtil.println("copyFile", "删除文件失败");
            }
        }
        if(!dest.createNewFile()){
            LogUtil.println("copyFile", "创建文件失败");
        }
        FileChannel outputChannel = null;
        FileChannel inputChannel = null;
        try {
            inputChannel = new FileInputStream(fileFrom).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            inputChannel.transferTo(0, inputChannel.size(), outputChannel);
            inputChannel.close();
        } finally {
            if (inputChannel != null) inputChannel.close();
            if (outputChannel != null) outputChannel.close();
        }
    }
}
