Reputation: 1627
Is there a way in java to orphan inodes so that the os can clean them up?
My goal is to recursively delete a folder, but it doesn't matter when it's deleted, just that it is. Since deleting it in time takes a while and slows me down, I've been using File.deleteOnExit()
, but that leaves the directory skeleton in place. Are there any solutions that can do this? This is currently what I do:
public static void markAllForDeletion(String folderName){
String newName = folderName + " " + UUID.randomUUID().toString();
new File(folderName).renameTo(new File(newName));
markBelow(new File(newName));
}
public static void markBelow(File folder){
for(File file: folder.listFiles()){
if(file.isDirectory()){
markBelow(file);
} else {
file.deleteOnExit();
}
}
folder.deleteOnExit();
}
Upvotes: 1
Views: 56
Reputation: 55589
Mark the folder for deletion before marking any of the folder contents:
public static void markBelow(File folder){
folder.deleteOnExit();
for(File file: folder.listFiles()){
if(file.isDirectory()){
markBelow(file);
} else {
file.deleteOnExit();
}
}
}
This is because the deletes from deleteOnExit
take place in reverse order, as per the docs:
Files (or directories) are deleted in the reverse order that they are registered.
Upvotes: 2