A standalone program that deletes a specified file or directory : Directory « File Input Output « Java

A standalone program that deletes a specified file or directory

 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.com/javaexamples3.

import java.io.File;

 * This class is a static method delete() and a standalone program that deletes
 * a specified file or directory.
public class Delete {
   * This is the main() method of the standalone program. After checking it
   * arguments, it invokes the Delete.delete() method to do the deletion
  public static void main(String[] args) {
    if (args.length != 1) { // Check command-line arguments
      System.err.println("Usage: java Delete <file or directory>");
    // Call delete() and display any error messages it throws.
    try {
    } catch (IllegalArgumentException e) {

   * The static method that does the deletion. Invoked by main(), and designed
   * for use by other programs as well. It first makes sure that the specified
   * file or directory is deleteable before attempting to delete it. If there is
   * a problem, it throws an IllegalArgumentException.
  public static void delete(String filename) {
    // Create a File object to represent the filename
    File f = new File(filename);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
      fail("Delete: no such file or directory: " + filename);
    if (!f.canWrite())
      fail("Delete: write protected: " + filename);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
      String[] files = f.list();
      if (files.length > 0)
        fail("Delete: directory not empty: " + filename);

    // If we passed all the tests, then attempt to delete it
    boolean success = f.delete();

    // And throw an exception if it didn't work for some (unknown) reason.
    // For example, because of a bug with Java 1.1.1 on Linux,
    // directory deletion always fails
    if (!success)
      fail("Delete: deletion failed");

  /** A convenience method to throw an exception */
  protected static void fail(String msg) throws IllegalArgumentException {
    throw new IllegalArgumentException(msg);


Related examples in the same category

1.Create directory
2.Create directory along with required nonexistent parent directories
3.Create directory tree (nested/cascade folders)
4.Create a directories recursively
5.Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
6.Delete a non-empty directory: Deletes all files and subdirectories under dir.
7.Listing the Files or Subdirectories in a Directory
8.Listing the File System Roots
9.The Directory Listing ApplicationThe Directory Listing Application
10.use list( ) to examine the contents of a directory:
11.Reading and Printing a Directory HierarchyReading and Printing a Directory Hierarchy
12.Display a file system in a JTree viewDisplay a file system in a JTree view
13.File Tree DemoFile Tree Demo
14.File Table HTMLFile Table HTML
15.Get Last modification time of a file or directory
16.Set last modified time of a file or directory
17.List contents of a directory
18.Determine if file or directory exists
19.Determine if File or Directory is hidden
20.Check if a directory is not empty
21.Get name of parent directory
22.Get name of specified file or directory
23.Get current directory
24.Mark file or directory Read Only
25.Rename file or directory
26.Traversing all files and directories under dir
27.Traversing only directories under dir
28.Traversing only files under dir
29.Creates and displays a window containing a list of files and sub-directories in a specified directory
30.Calculate directory size
31.Delete directory recursively
32.Determining If Two Filename Paths Refer to the Same File
33.Recursive directory deletion
34.Recursivly delete directory
35.Searches through the directory tree
36.Starts at the directory given and tests to see whether it is empty
37.Directory Walker
38.Utility methods for handling files and directories
39.Creates a new and empty directory in the default temp directory using the given prefix.
40.Count files in a directory (including files in all subdirectories)
41.Create a unique directory within a directory 'root'
42.Creates a new empty temporary directory.
43.Get Files Recurse
44.Recursively search a directory tree
45.Find directoriesFind directories