无法通过Java删除目录

Vip*_*pul 12 java

在我的应用程序中,我编写了从驱动器中删除目录的代码,但是当我检查File的删除功能时,它不会删除该文件.我写了一些像这样的东西

//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete(); 
Run Code Online (Sandbox Code Playgroud)

目录未使用仍然无法删除目录

Rid*_*del 22

在Java中,目录删除仅适用于空目录,这会导致以下方法:

/**
 * 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());
}
Run Code Online (Sandbox Code Playgroud)

这个将删除你的文件夹,即使是非空的,没有麻烦(当该目录被OS锁定时除外).


Ilj*_* S. 15

为什么要发明一个带有递归删除方法的轮子?看看apache commons io. https://commons.apache.org/proper/commons-io/javadocs/api-1.4/

FileUtils.deleteDirectory(dir);
Run Code Online (Sandbox Code Playgroud)

要么

FileUtils.forceDelete(dir);
Run Code Online (Sandbox Code Playgroud)

这就是你所需要的一切.还有很多有用的方法来操作文件......