Java Delete File Recursively deleteRecursively(File fRoot)

Here you can find the source of deleteRecursively(File fRoot)

Description

Deletes all files and directories under the given directory.

License

Apache License

Parameter

Parameter Description
fRoot The root directory to be deleted.

Exception

Parameter Description
IOExceptionThrown if the deletion operation failed.

Declaration

public static void deleteRecursively(File fRoot) throws IOException 

Method Source Code

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

import java.io.File;

import java.io.IOException;

public class Main {
    /**//from  ww  w . j  a  v a  2 s.co m
     * Deletes all files and directories under the given directory.
     *
     * @param   fRoot  The root directory to be deleted.
     *
     * @throws  IOException  Thrown if the deletion operation failed.
     */
    public static void deleteRecursively(File fRoot) throws IOException {
        if (fRoot == null) {
            throw new NullPointerException("Root folder is null.");
        }

        // Check if the root is a file.
        if (fRoot.isFile()) {
            // Try to delete it.
            if (!fRoot.delete()) {
                // The deletion failed.
                throw new IOException("Unable to delete file '" + fRoot.getAbsolutePath() + "'");
            }

            return;
        }

        // List all files and directories under this directory.
        File[] faFiles = fRoot.listFiles();

        for (int iIndex = 0; iIndex < faFiles.length; iIndex++) {
            File fFile = faFiles[iIndex];

            // Call this method recursively
            deleteRecursively(fFile);
        }

        // Try to delete folder.
        if (!fRoot.delete()) {
            // The deletion failed.
            throw new IOException("Unable to delete folder '" + fRoot.getAbsolutePath() + "'");
        }
    }
}

Related

  1. deleteRecursively(File file)
  2. deleteRecursively(File fileEntry)
  3. deleteRecursively(File fileOrDir)
  4. deleteRecursively(File fileOrDir)
  5. deleteRecursively(File fileToDelete)
  6. deleteRecursively(File name)
  7. deleteRecursively(File root)
  8. deleteRecursively(File root)
  9. deleteRecursively(File root, boolean deleteRoot)