Java Delete Directory deleteDirectory(File dir)

Here you can find the source of deleteDirectory(File dir)

Description

Deletes a directory and all of its contents.

License

Open Source License

Parameter

Parameter Description
dir the reference to a directory or a file

Return

true if everything was deleted, false if at least one item could not be deleted.

Declaration

public static boolean deleteDirectory(File dir) 

Method Source Code

//package com.java2s;
/*//w  ww . j  a va  2  s  .  co  m
 * Copyright (c) 2006 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial API and implementation
 */

import java.io.File;

import java.util.Stack;

public class Main {
    /**
     * Deletes a directory and all of its contents.
     * 
     * <p>Simple,Quick, No Frills approach to wiping out a directory. See 
     * {@linkplain #clearDir(File, boolean, boolean)} for a method with more 
     * frills.</p>
     * 
     * @param dir the reference to a directory or a file
     * 
     * @return true if everything was deleted, false if at least one item could not be deleted.
     * 
     * @see #clearDir(File, boolean, boolean)
     */
    public static boolean deleteDirectory(File dir) {
        boolean retval = true;
        File[] currList;
        Stack<File> stack = new Stack<File>();
        stack.push(dir);

        // while we still have things to delete
        while (!stack.isEmpty()) {

            // if the next item is a directory
            if (stack.lastElement().isDirectory()) {
                // get a listing of all the files and directories
                currList = stack.lastElement().listFiles();

                // place everything found on the stack
                if (currList.length > 0) {
                    for (File curr : currList) {
                        stack.push(curr);
                    }
                } else {
                    // there is nothing in this directory so it can be deleted
                    if (!stack.pop().delete())
                        retval = false;
                }
            } else {
                // this is a file, so delete it
                if (!stack.pop().delete())
                    retval = false;
            }
        }
        return retval;
    }
}

Related

  1. deleteDirectory(File dir)
  2. deleteDirectory(File dir)
  3. deleteDirectory(File dir)
  4. deleteDirectory(File dir)
  5. deleteDirectory(File dir)
  6. deleteDirectory(File dir, boolean isInitialDelete)
  7. deleteDirectory(File dir, boolean isInitialDelete)
  8. deleteDirectory(File dir, boolean recursive)