Using Java, I’m trying to delete files and folders on a NAS. Everything works perfectly, except when a user has opened Windows Explorer in a folder I want to delete.
For example, I have a folder A which contains a folder B. I want to delete folder B and then folder A. Folder B will be deleted, but not folder A. This only happens when someone uses Windows Explorer in folder B. My code says that folder A is not empty, it still contains folder B. But how can this be because folder B has just been deleted, and in Windows Explorer I can’t see folder B (even though hidden files are checked).
I’ve tried running this code locally and it works even though I have Windows Explorer open in folder B. This only happens with the NAS. Do you have any ideas?
void test(){
isSuccessfullyRemoved = true
Path p = Paths.get('FOLDER B')
try (def ds = Files.newDirectoryStream(p)) {
ds.each { subPath ->
// Delete every files in the folder B
if (subPath.toFile().isFile()) {
deleteFileorFolder(subPath)
}
}
}
// The folder B should be empty if the deletion of the files was successful and does not contains a folder
if (isSuccessfullyRemoved && isDirEmpty(p)) {
// Delete Folder B
deleteFileorFolder(p)
// Folder B has been deleted, isSuccessfullyRemoved is TRUE but isDirEmpty is FALSE, why?
if (isSuccessfullyRemoved && isDirEmpty(p.parent)) {
deleteDirectory(p.parent.toFile())
}
}
}
boolean isDirEmpty(Path directory) {
try (def ds = Files.newDirectoryStream(directory)) {
return !ds.iterator().hasNext()
}
}