not able to delete the directory through Java

后端 未结 5 1543
执念已碎
执念已碎 2021-02-13 06:59

In my application I have written the code to delete the directory from drive but when I inspect the delete function of File it doesn\'t delete the file. I have written some thin

5条回答
  •  一个人的身影
    2021-02-13 07:43

    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).

提交回复
热议问题