not able to delete the directory through Java

Why to invent a wheel with methods to delete recursively? Take a look at apache commons io. https://commons.apache.org/proper/commons-io/javadocs/api-1.4/

FileUtils.deleteDirectory(dir);

OR

FileUtils.forceDelete(dir);

That is all you need. There is also plenty of useful methods to manipulate files...


in Java, directory deletion is possible only for empty directory, which leads to methods like the following :

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}

This one will delete your folder, even if non-empty, without troubles (excepted when this directory is locked by OS).

Tags:

Java