• Java 当文件不存在时自动创建文件目录和文件


    操作文件流的时候,经常遇到在新目录中创建文件的场景,因此,这里记录如何判断文件是否存在,如果不存在,则如何创建目录和文件。

        public static void main(String[] args) {
            // 可以是任意格式的文件
            String pathName = "D:\img\test2.txt";
            createFile(new File(pathName));
           
        }
    
    
    
        /**
         * 判断文件是否存在,不存在就创建
         * @param file
         */
        public static void createFile(File file) {
            if (file.exists()) {
                System.out.println("File exists");
            } else {
                System.out.println("File not exists, create it ...");
                //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
                if (!file.getParentFile().exists()) {
                    System.out.println("not exists");
                    //创建上级目录
                    file.getParentFile().mkdirs();
                }
                try {
                    //在上级目录里创建文件
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    

      读后有收获,小礼物走一走,请作者喝咖啡。

    赞赏支持

  • 相关阅读:
    Log4Net记录到MySql
    创建快照
    grep的用法(CentOS7)及有关正则表达式的使用
    samba
    mkdir
    raid0和raid5的 实验过程
    route
    source和sh执行脚本时的差异
    echo命令的简单用法和实例
    smbpasswd和pdbedit
  • 原文地址:https://www.cnblogs.com/east7/p/15456848.html
Copyright © 2020-2023  润新知