I’m trying to do a simple method that deletes a file its upper directories if they are empty till it reaches a base directory, but I cannot make it work.
It deletes the file, its parent directory, but, its next parent isn’t deleted as it throws a DirectoryNotEmptyException. It really is empty as there was only one child directory and it was deleted in the previous iteration.
So, the file is deleted, its parent is deleted, and it stops there, no more upper directories are deleted.
EDITED: (modified code)
It seems that there is a delay deleting directories, so in the next check of the emptiness state of the directory, the previous one isn’t yet deleted. So I’ve added a while loop to check until the directory doesn’t exist. I don’t know if this is it or not a bad technique but it works for my needs.
public static void removeFileAndParentsIfEmpty(Path path) throws IOException {
if(path == null || path.endsWith(FilesPath.BILLS_DIRECTORY)) {
return;
}
if (Files.isRegularFile(path)){
Files.deleteIfExists(path);
} else if (Files.isDirectory(path)){
if(path.toFile().list().length == 0){
Files.delete(path);
while(Files.exists(path));
}else{
return;
}
} else {
return;
}
removeFileAndParentsIfEmpty(path.getParent());
}
If anyone can give a better solution, the question is still open for approval.
Thanks.
You don’t have a base condition for an empty directory, so on the second go-through your recursive function it attempts to delete the empty directories parent, before the directory itself. A simple code change should be sufficient to fix this: