Suppose I have I directory structure like the following:
MyDirectory
> File1
> File2
> File3
> UndeletableFile
> File4
Suppose also that I have already implemented a recursive algorithm for deleting the content of a folder and then the folder itself and/or used one of the excellent suggestions here
Now here's the catch to which I can't seem to find a solution after some searching on the web and on SO:
I want to delete the entire folder, but I want to do it only if it will succeed for every file and subfolder that is in there. The current implementation (of java.io.File.delete()
to be precise) will delete a file immediately upon being called on it and then move on to the next file. If the deletion of a folder fails halfway through like in the example above there will be UndeletableFile
and File5
as well as MyDirectory
left on the system.
Is there a convenince method or a best practise algorithm for this case?
The goal is to let the deletable files live if the operation would fail halfway through. After all they shouldn't die if their home will survive, right?
What I have thought about so far:
Maybe it would be smart to just rename all files first instead of deleting them, like so
MyDirectory
> File1temp
> File2temp
> ...
After that if the process fails I could traverse the directory again and re-rename all files back to normal and if it succeeds I could delete them for good.
But this seams very inefficient to me, isn't there a better solution? It seems to me like this should be a common problem, please provide a link if I have overlooked something