java File 自动创建所有目录

来源:互联网 发布:车载音乐视频软件 编辑:程序博客网 时间:2024/06/05 06:34
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class UtilsFile {

    /**
     * write String to File,
     * 如果要创建的目录不存在,则自动创建所有目录
     * @param filePath 要以反斜杠分割路径:'/'
     * @param flag
     * @param sb
     */
    public void writeToFile(String filePath, boolean flag, String sb) {
        File file = new File(filePath);
        if (flag) {
            String[] split = filePath.split("/");
            String fileDir = filePath.replace(split[split.length - 1], "");
            File file2 = new File(fileDir);
            if (!file2.exists()) {
                file2.mkdirs();
            }
        }
        FileOutputStream out = null;
        try {

            out = new FileOutputStream(file);
            out.write(sb.getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}


原创粉丝点击