Empty and delete a folder (and subfolders) in Java

Description

The following code shows how to empty and delete a folder (and subfolders).

Example


/* w  w w.  j a  v  a2  s. c  om*/
import java.io.File;

public class Main {
  /**
   * Empty and delete a folder (and subfolders).
   * @param folder
   *            folder to empty
   */
  public static void rmdir(final File folder) {
      // check if folder file is a real folder
      if (folder.isDirectory()) {
          File[] list = folder.listFiles();
          if (list != null) {
              for (int i = 0; i < list.length; i++) {
                  File tmpF = list[i];
                  if (tmpF.isDirectory()) {
                      rmdir(tmpF);
                  }
                  tmpF.delete();
              }
          }
          if (!folder.delete()) {
            System.out.println("can't delete folder : " + folder);
          }
      }
  }
}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip