Java File Path Delete deleteRecursive(File path)

Here you can find the source of deleteRecursive(File path)

Description

By default File#delete fails for non-empty directories, it works like "rm".

License

Apache License

Parameter

Parameter Description
path Root File Path

Exception

Parameter Description
FileNotFoundException an exception

Return

true iff the file and all sub files/directories have been removed

Declaration

public static boolean deleteRecursive(File path) throws FileNotFoundException 

Method Source Code


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

import java.io.File;
import java.io.FileNotFoundException;

public class Main {
    public static boolean deleteRecursive(String path) throws FileNotFoundException {
        File file = new File(path);
        return deleteRecursive(file);
    }//from  w  w w  .j  a va 2  s . c  o  m

    /**
     * By default File#delete fails for non-empty directories, it works like "rm". We need something a little more brutual
     * - this does the equivalent of "rm -r"
     *
     * @param path Root File Path
     * @return true iff the file and all sub files/directories have been removed
     * @throws FileNotFoundException
     */
    public static boolean deleteRecursive(File path) throws FileNotFoundException {
        if (!path.exists()) {
            throw new FileNotFoundException(path.getAbsolutePath());
        }
        boolean ret = true;
        if (path.isDirectory()) {
            for (File f : path.listFiles()) {
                ret = ret && deleteRecursive(f);
            }
        }
        return ret && path.delete();
    }
}

Related

  1. deletePath(File dirPath)
  2. deletePath(File path)
  3. deletePath(final File path)
  4. deletePathRecursive(File path)
  5. deleteQuietly(Object path)
  6. deleteRecursive(File path)
  7. deleteRecursive(File path)
  8. deleteRecursive(File path)
  9. deleteRecursive(File path)