java实现File的创建(Document learning —one)

File.separator 输出的值:" / "
package com.file;

import java.io.File;
import java.io.IOException;

public class CreateFile {

    /**
     * 创建文件
     * @param destFileName
     * @return
     */
    public static boolean createFile(String destFileName) {
        File file = new File(destFileName);
        if (file.exists()) {
            System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
            return false;
        }
        if (destFileName.endsWith(File.separator)) {
            System.out.println("创建单个文件" + destFileName + "失败,目标不能是目录!");
            return false;
        }
        if (!file.getParentFile().exists()) {
            System.out.println("目标文件所在路径不存在,准备创建。。。");
            if (!file.getParentFile().mkdirs()) {
                System.out.println("创建目录文件所在的目录失败!");
                return false;
            }
        }

        // 创建目标文件
        try {
            if (file.createNewFile()) {
                System.out.println("创建单个文件" + destFileName + "成功!");
                return true;
            } else {
                System.out.println("创建单个文件" + destFileName + "失败!");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建单个文件" + destFileName + "失败!");
            return false;
        }
    }
}

 

posted @ 2020-04-06 20:48  An-Optimistic-Person  阅读(464)  评论(0)    收藏  举报