1 package j2se.core.io.file; 2 3 4 import java.io.File; 5 import java.io.IOException; 6 7 /** 8 * File(目录) 使用入门范例 9 */ 10 public class DirectoryDemo { 11 12 public static void main(String[] args) { 13 File dir = new File("src/j2se/core/io/file"); 14 if (dir.isDirectory()) { 15 System.out.println(dir + " 是个目录"); 16 } 17 18 //遍歷文件夾所有的文件,但是不會遞歸 19 for (String s : dir.list()) { 20 System.out.println(s); 21 } 22 23 createSingleDir("src/j2se/core/io/file/test1"); 24 deleteSingleDir("test1"); 25 26 createMultiDir("test2/dir"); 27 deleteMultiDir("test2"); 28 29 createFileWithDir("test3/a.txt"); 30 deleteMultiDir("test3"); 31 } 32 33 /** 创建文件的同时创建目录 */ 34 private static void createFileWithDir(String string) { 35 File file = new File(string); 36 if (file.exists()) 37 return; 38 File dir = file.getParentFile(); 39 if (!dir.exists()) 40 dir.mkdirs(); 41 try { 42 file.createNewFile(); 43 System.out.println("文件与目录创建成功!"); 44 } catch (IOException e) { 45 System.out.println("文件或目录创建失败!"); 46 } 47 } 48 49 /** 删除目录树 */ 50 private static void deleteMultiDir(String string) { 51 File dir = new File(string); 52 if (!dir.exists()) 53 return; 54 if (delete(dir)) 55 System.out.println("删除成功!"); 56 else 57 System.out.println("删除失败!"); 58 } 59 60 /** 递归删除文件或目录 */ 61 private static boolean delete(File current) { 62 boolean flag = true; 63 if (current.isDirectory()) 64 for (File file : current.listFiles()) 65 flag = flag && delete(file); 66 return flag && current.delete(); 67 } 68 69 /** 创建目录树 */ 70 private static void createMultiDir(String string) { 71 File dir = new File(string); 72 if (dir.exists()) 73 return; 74 if (dir.mkdirs()) 75 System.out.println("目录树创建成功!"); 76 else 77 System.out.println("目录树创建失败!"); 78 } 79 80 /** 删除单一目录 */ 81 private static void deleteSingleDir(String string) { 82 File dir = new File(string); 83 if (!dir.exists()) 84 return; 85 if (dir.delete()) 86 System.out.println("删除成功!"); 87 else 88 System.out.println("删除失败!"); 89 } 90 91 /** 创建单一目录 */ 92 private static void createSingleDir(String string) { 93 File dir = new File(string); 94 if (dir.exists()) 95 return; 96 if (dir.mkdir()) 97 System.out.println("目录创建成功!"); 98 else 99 System.out.println("目录创建失败!"); 100 } 101 }
重点需要理解的是递归删除怎么做,其他的就是引用简单的方法。
一层一层的向下遍历,当遍历到没有文件夹时就执行上 一段代码的方法删除,再从头遍历,碰到空文件夹和问价就删除。
1 /** 删除目录树,删除下面一段代码递归删除后的空文件夹 */ 2 private static void deleteMultiDir(String string) { 3 File dir = new File(string); 4 if (!dir.exists()) 5 return; 6 if (delete(dir)) 7 System.out.println("删除成功!"); 8 else 9 System.out.println("删除失败!"); 10 } 11 12 13 14 15 16 /** 递归删除文件或目录 */ 17 private static boolean delete(File current) { //定义静态的删除方法,参数current 18 boolean flag = true; //定义flag 19 if (current.isDirectory()) //判断是否为文件夹 20 for (File file : current.listFiles()) //遍历当前文件,返回的为目录中的文件 21 flag = flag && delete(file); //这句就是最关键的,flag为退出的标志,判断为文件夹内有文件,则继续执行delete方法,继续遍历,直到判断为flase 22 return flag && current.delete(); //当遍历出没有下层目录判断值为false,执行delete方法 23 }