Xóa thư mục trong Java



Miêu tả vấn đề

Cách xóa một thư mục trong Java?

Giải pháp

Ví dụ sau minh họa cách xóa một thư mục sau khi xóa các file và thư mục của nó bởi sử dụng phương thức ofdir.isDirectory(), dir.list() và deleteDir() của lớp File trong Java.

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.");
  }
}

Kết quả

Code trên sẽ cho kết quả sau:

The directory is deleted.

thu_muc_trong_java.jsp