Java I/O How to - Delete all files and directories under a folder recursively








Question

We would like to know how to delete all files and directories under a folder recursively.

Answer

/*from ww  w . j  av a 2  s .  c  om*/
import java.io.File;
import java.io.IOException;

public class Main {
  /**
   * 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);

}

Another solution.

/* w ww  .  jav  a2  s . c o  m*/
/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
  
  /**
   * Deletes the specified diretory and any files and directories in it
   * recursively.
   * 
   * @param dir The directory to remove.
   * @throws IOException If the directory could not be removed.
   */
  public static void deleteDir(File dir)
    throws IOException
  {
    if (!dir.isDirectory()) {
      throw new IOException("Not a directory " + dir);
    }
    
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
      File file = files[i];
      
      if (file.isDirectory()) {
        deleteDir(file);
      }
      else {
        boolean deleted = file.delete();
        if (!deleted) {
          throw new IOException("Unable to delete file" + file);
        }
      }
    }
    
    dir.delete();
  }

}