package day08File;
import java.io.File;
import java.io.IOException;
/*
File类创建删除功能的方法
- public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。
- public boolean delete() :删除由此File表示的文件或目录。
- public boolean mkdir() :创建由此File表示的目录。
- public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录。(创建多级目录)
*/
public class Test02 {
public static void main(String[] args) throws IOException {
show01();//- public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空文件。
show02();//- public boolean delete() :删除由此File表示的文件或目录。
show03();
}
private static void show03() {
File f1 = new File("D:\\phpstudy_pro\\test\\aaa");
System.out.println(f1.mkdir());//创建单级目录返回true
File f2 = new File("D:\\phpstudy_pro\\test\\111\\222\\333");
System.out.println(f2.mkdirs());//创建多级目录,返回true
f1.delete();
f2.delete();
File f3 = new File("D:\\phpstudy_pro\\test\\111");
System.out.println(f3.delete());//需要注意的是delete不能删除包含文件/文件夹的文件夹,需要子文件夹一层一层删除
}
private static void show02() {
File f1 = new File("D:\\phpstudy_pro\\test\\1.txt");
System.out.println(f1.delete());//删除前文件存在,则true
File f2 = new File("D:\\phpstudy_pro\\test\\1.txt");
System.out.println(f2.delete());//文件不存在,返回false
}
private static void show01() throws IOException {
File f1 = new File("D:\\phpstudy_pro\\test\\1.txt");
System.out.println(f1.createNewFile());//文件不存在创建成功后显示true
File f2 = new File("D:\\phpstudy_pro\\test\\1.txt");
System.out.println(f2.createNewFile());//路径错误,会抛出异常
}
}
File类创建删除功能的方法
最新推荐文章于 2022-09-05 12:33:04 发布