Java Recursive Delete recursivelyDelete(final File root, final boolean deleteRoot)

Here you can find the source of recursivelyDelete(final File root, final boolean deleteRoot)

Description

Recursively deletes the contents of the given directory (and possibly the directory itself).

License

Open Source License

Parameter

Parameter Description
root directory (or file) whose contents will be deleted
deleteRoot true deletes root directory, false deletes only its contents.

Exception

Parameter Description
IOException if something goes wrong, which may leave thingsin an inconsistent state.

Declaration

public static void recursivelyDelete(final File root, final boolean deleteRoot) throws IOException 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.IOException;

public class Main {
    /**//from  w  ww .java  2s .co  m
     * Recursively deletes the contents of the given directory (and
     * possibly the directory itself).
     *
     * @param root directory (or file) whose contents will be deleted
     * @param deleteRoot true deletes root directory, false deletes only
     *  its contents.
     *
     * @throws IOException if something goes wrong, which may leave things
     *   in an inconsistent state.
     */
    public static void recursivelyDelete(final File root, final boolean deleteRoot) throws IOException {
        if (root.isDirectory()) {
            final File[] contents = root.listFiles();
            for (final File child : contents) {
                recursivelyDelete(child, true);
            }
        }
        if (deleteRoot) {
            if (!root.delete()) {
                throw new IOException("Could not delete directory " + root);
            }
        }
    }

    /**
     * Convenience version of {@link #recursivelyDelete(File, boolean)} that
     * deletes the given root directory as well.
     */
    public static void recursivelyDelete(final File root) throws IOException {
        recursivelyDelete(root, true);
    }
}

Related

  1. recursiveDeleteOnExit(File parent)
  2. recursiveDeleteOnExit(File rootDir)
  3. recursiveDeleteOnExitHelper(File fileOrDir)
  4. recursivelyDelete(File aDirectory)
  5. recursivelyDelete(File dir)
  6. recursivelyDelete(String loc)
  7. recursivelyDeleteEmptyDirectories(File fileToDelete)
  8. recursivelyDeleteEmptyParentDirectoriesUpToRoot(String path, String root)
  9. recursivelyDeleteFile(File path)