获取File对象
这里的字符串可以乱写,但是如果不存在后续的操作也会失败
// 获取抽象的File对象(文件或者目录,不一定真实存在)
File file1 = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath");
System.out.println(file1.getName());
System.out.println(file2.getName());
// 用exist判断文件/文件夹是否存在
boolean file1Exist = file1.exists();
System.out.println(file2Exist);
创建文件/文件夹
// 创建文件,重复创建会报错(先判断是否存在)
boolean isFile2Create = file2.createNewFile();
System.out.println(isFile2Create);
boolean isFile3Create = file3.createNewFile();
System.out.println(isFile3Create);
// 创建文件夹,重复创建会报错(先判断是否存在)
File path1 = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath\\pathCreate");
boolean isPath1Create = path1.mkdir();
System.out.println(isPath1Create);
删除
// 删除文件/目录
File wordFile = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath\\新建 Microsoft Word 文档.docx");
boolean wordDelete = wordFile.delete();
System.out.println(wordDelete);
递归遍历
递归遍历打印文件名/目录名
public static void printFileAllChilds(File file) {
if (file == null || !file.exists()) {
return;
}
//给层级来加一
level++;
if (file.isDirectory()) {
File[] fileArr = file.listFiles();
for (File child : fileArr) {
printFileAllChilds(child);
}
} else {
//打印层级的缩进
for (int i = 0; i < level; i++)
System.out.print("\t");
System.out.println(file.getName());
}
//本层次遍历完毕把层级减回来
level--;
}
我们假设打印D盘
File fileToPrint = new File("D://");
输出结果
递归遍历并删除文件夹下所有的文件(不删除目录)
谨慎选择File的路径,不要选择特别大的范围,比如整个C盘或者D盘,运行此代码出现的一切后果请读者自负!!!
public static void deleteFileChilds(File file) {
if (file == null || !file.exists()) {
return;
}
if (file.isDirectory()) {
File[] fileArr = file.listFiles();
for (File child : fileArr) {
deleteFileChilds(child);
}
} else {
System.out.println(file.getName());
file.delete();
}
}
我这里选择的File是一个很小的文件夹
File fileToDelete = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath");