Java Delete Directory deleteDirectoryContents(final File dir)

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

Description

Recursively deletes all files and folders within the directory dir.

License

Apache License

Parameter

Parameter Description
dir File , the directory to empty contents for

Return

boolean determines whether or not the delete was successful, true if success, false otherwise

Declaration

public static boolean deleteDirectoryContents(final File dir) 

Method Source Code


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

import java.io.*;

public class Main {
    /**/* w ww.  j a va  2  s. c  o m*/
     * 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;
    }

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

Related

  1. deleteDirectoryContents(File directory)
  2. deleteDirectoryContents(File directory)
  3. deleteDirectoryContents(File directory)
  4. deleteDirectoryContents(File directory)
  5. deleteDirectoryContents(File directory)
  6. deleteDirectoryContents(final File dir, int deleteDirLevel, int level)
  7. deleteFiles(File dir)
  8. deleteFiles(File dir)
  9. deleteFiles(File directory)