package net.northking.cctp.element.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * FileUtils
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public class FileUtils {

    public static boolean deleteFile(File file) {
        if (!file.exists()) {
            return false;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
        }
        return file.delete();
    }

    public static File writeFile(InputStream is, String path) throws Exception {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] chs = new byte[1024];
            int len;
            while ((len = is.read(chs)) != -1) {
                os.write(chs, 0, len);
            }
            return file;
        } finally {
            IOUtils.close(is, os);
        }
    }

}
