Delete all files under this file and including this file : Delete « File Input Output « Java






Delete all files under this file and including this file

 
import java.io.File;
import java.io.IOException;

public class Utils {
  /**
   * delete all files under this file and including this file
   * 
   * @param f
   * @throws IOException
   */
  public static void deleteAll(File f) throws IOException {
    recurse(f, new RecurseAction() {
      public void doFile(File file) throws IOException {
        file.delete();
        if (file.exists()) {
          throw new IOException("Failed to delete  " + file.getPath());
        }
      }

      public void doBeforeFile(File f) {
      }

      public void doAfterFile(File f) {
      }
    });
  }

  public static void recurse(File f, RecurseAction action) throws IOException {
    action.doBeforeFile(f);
    if (f.isDirectory()) {
      File[] files = f.listFiles();
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          if (files[i].isDirectory()) {
            recurse(files[i], action);
          } else {
            action.doFile(files[i]);
          }
        }
      }
    }
    action.doFile(f);
  }
}

interface RecurseAction {

  /**
   * @param file
   * @throws IOException
   */
  void doFile(File file) throws IOException;

  /**
   * @param f
   */
  void doBeforeFile(File f);

  /**
   * @param f
   */
  void doAfterFile(File f);

}

   
  








Related examples in the same category

1.Deletes all files and subdirectories
2.Remove file or directory
3.Utilities for file delete copy close
4.Deletes the diretory and any files and directories in it recursively.
5.Delete Recursively
6.Delete a file
7.Delete the file or non-empty directory at the supplied path
8.Deletes a directory.
9.Recursively delete a file and all its contents
10.Empty and delete a folder (and subfolders).