如何删除目录?(How to delete a directory?)

优质
小牛编辑
130浏览
2023-12-01

问题描述 (Problem Description)

如何删除目录?

解决方案 (Solution)

下面的示例演示如何通过使用File类的dia.isDirectory(),dir.list()和deleteDir()方法删除其文件和目录后删除目录。

import java.io.File;
public class Main {
   public static void main(String[] argv) throws Exception {
      deleteDir(new File("c:\\temp"));
   }
   public static boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
         String[] children = dir.list();
         for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir (new File(dir, children[i]));
            if (!success) {
               return false;
            }
         }
      }
      return dir.delete();
      System.out.println("The directory is deleted.");
   }
}

结果 (Result)

上面的代码示例将产生以下结果。

The directory is deleted.