java file does not exist automatically create file java file exists

Table of contents

1. Determine whether the file exists

2. Determine whether the folder exists

2.1, the folder created by file.mkdirs()

2.2、 file.getParentFile().mkdirs();


1. Determine whether the file exists

import java.io.File;

public class dome {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\upload\protocol");
        if(file.exists()){
            System.out.println("文件存在");
            file.delete();//删除文件
        }else{
            System.out.println("文件不存在");
            file.createNewFile();//创建失败会抛出异常throw new IOException("Invalid file path");
        }
    }
}

2. Determine whether the folder exists

public class dome {
    public static void main(String[] args) throws Exception {
        File file = new File("E:\upload\protocol");
        if(!file.exists()&& !file.isDirectory()){
            System.out.println("文件夹不存在");
            file.mkdirs();                        //把a.sql也当做文件夹名来创建
            file.getParentFile().mkdirs();       //获取路径的根路径领创建文件,到最后最后一级路径前E:\新建文件夹\20211110\
        }else{
            System.out.println("文件夹存在");
        }
    }
}

2.1, the folder created by file.mkdirs()

 2.2、 file.getParentFile().mkdirs();

 

Guess you like

Origin blog.csdn.net/weixin_52208686/article/details/131896852