场景

进行文件相关操作时,经常用到文件路径的判空。比如:

String path = storePath +"\\"+ newName;
File file2 =new File(storePath);

if(!file2.exists()){
file2.mkdirs();
}

实现

createNewFile()

用于创建文件,不包括文件夹。

mkdir()

用于创建指定路径的上一层目录。

mkdirs()

用于创建指定路径的多层目录。

示例代码

String templatePath="D:"+File.separator+"kurt";

File file=new File(templatePath);
if (!file.exists()){
file.mkdirs();
}
String template=templatePath+File.separator+"test.txt";
File file2=new File(template);
if (!file2.exists()){
file2.createNewFile();
}