Java Delete Directory deleteDirectory(final File dir)

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

Description

Deletes the directory dir , and all of its contents.

License

Apache License

Parameter

Parameter Description
dir File

Return

boolean true if success, false otherwise

Declaration

public static boolean deleteDirectory(final File dir) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**//  w w  w .  j a va 2  s. co  m
     * Deletes the directory {@code dir}, and all of its contents.
     *
     * @param dir {@link File}
     * @return boolean {@code true} if success, {@code false} otherwise
     */
    public static boolean deleteDirectory(final File dir) {
        if (!deleteDirectoryContents(dir)) {
            return false;
        }

        return dir.delete();
    }

    /**
     * Recursively deletes all files and folders within the directory
     * <tt>dir</tt>.
     *
     * @param dir {@link File}, the directory to empty contents for
     * @return boolean determines whether or not the delete was successful,
     *         <tt>true</tt> if success, <tt>false</tt> otherwise
     */
    public static boolean deleteDirectoryContents(final File dir) {
        if (dir == null || !dir.isDirectory()) {
            return false;
        }

        File[] files = dir.listFiles();
        for (final File file : files) {
            if (file.isDirectory()) {
                if (!deleteDirectory(file)) {
                    return false;
                }
            } else {
                if (!file.delete()) {
                    return false;
                }
            }
        }

        return true;
    }
}

Related

  1. deleteDirectory(File root)
  2. deleteDirectory(File root)
  3. deleteDirectory(File root)
  4. deleteDirectory(File sourceDirectory, FilenameFilter filter, boolean recursive, boolean deleteItself)
  5. deleteDirectory(final File dir)
  6. deleteDirectory(final File dir)
  7. deleteDirectory(final File directory)
  8. deleteDirectory(final File directory)
  9. deleteDirectory(final File directory)