开发者

Unable to delete directory after creating it

开发者 https://www.devze.com 2023-02-18 04:31 出处:网络
I\'m trying to sequentially create and then delete a directory. However, it appears that deleting the directory is not working.

I'm trying to sequentially create and then delete a directory. However, it appears that deleting the directory is not working.

Does anyone has idea of why? Is it due to the file system not being refreshed in Java?

public boolean createDirectory(File file) {
    // Delete Directory if alreday exists
    if (file.exists()) {
        deleteDirectory(file);
    }
    boolean status = file.mkdirs();
    if (status) {
        System.out.println(" Successfull of creating Directory " + file.getPath());
    }
    return status;
}

public boolean deleteDirectory(File dir) {
    if (dir.isDirec开发者_如何学Gotory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            File delFile = new File(dir, children[i]);
            if (!delFile.exists()) {
                System.out.println("Cannot find directory to delete" + delFile.getPath());
                return false;
            }
            boolean success = deleteDirectory(delFile);
            System.out.println(delFile + ": success? " + success);
            if (!success) {
                System.out.println("failure during delete directory" + delFile.getPath());
                return false;
            }
        }
        // The directory is now empty so now it can be smoked
        return dir.delete();
    }
}


If this is running on Windows, then the problem is usually that Windows won't delete a directory if any process is "using" it -- i.e., has a file from that directory (or one of its children) open, or has that directory (or one of its children) as its current working directory.


Rather than trying to create your own recursive delete method, I would suggest using one that is already well established. If you can, use Apache Commons IO FileUtils.deleteDirectory(java.io.File).

0

精彩评论

暂无评论...
验证码 换一张
取 消