Deletes the diretory and any files and directories in it recursively. : Delete « File Input Output « Java






Deletes the diretory and any files and directories in it recursively.

  
/*
 * 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();
  }

}

   
    
  








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.Delete Recursively
5.Delete a file
6.Delete all files under this file and including this 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).