Java delete a folder and subfolders recursively

Java source code for deleting a folder and subfolders recursively.
Code for copying and moving files is here.
Working source code example:
public final class FileIOUtility {
    private FileIOUtility() {}
    public static boolean deleteFile(File fileToDelete) {
        if (fileToDelete == null || !fileToDelete.exists()) {
            return true;
        } else {            boolean result = deleteChildren(fileToDelete);
            result &= fileToDelete.delete();
            return result;
        }
    }
    public static boolean deleteChildren(File parent) {
        if (parent == null || !parent.exists())
            return false;
        boolean result = true;
        if (parent.isDirectory()) {
            File files[] = parent.listFiles();
            if (files == null) {
                result = false;
            } else {
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    if (file.getName().equals(".") || file.getName().equals(".."))
                        continue;
                    if (file.isDirectory())
                        result &= deleteFile(file);
                    else
                        result &= file.delete();
                }

            }
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        // delete test on your risk
        deleteFile(new File("D:\\tmptest\\"));
    }
}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...