My objective is to delete a directory with all its children, including subdirectories and files upon VM exits.
I did a simple test and realized that File.deleteOnExit() will not work if the File denotes to a directory and the directory has contents. So I thought I can just recursively get all files and subdirectories of that directory and call all their deleteOnExit() method.
But the result wasn't what I expected. JVM just deleted all files but leave all directories there. How come this happen?
My testing codes are:
My environment is:
java version "1.4.2_04" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_04-b05) Java HotSpot(TM) Client VM (build 1.4.2_04-b05, mixed mode)
Can anybody help? Thanks in advance! [ December 19, 2007: Message edited by: vichy baby ]
I've checked the code for File.deleteOnExit, and it uses a package private class called DeleteOnExitHook. This will delete files in reversed order. So the last file to be called with deleteOnExit, will be deleted first. This is also specified in the API:
Files (or directories) are deleted in the reverse order that they are registered.
So if you call deleteOnExit for the directory, call it for the directory first, then its children.
Also, I'd make the delete method recursive as well:
Another option is to use Runtime.getRuntime().addShutdownHook(). This allows you to do just about anything you want to in the code (though you should read the API for this method to see warnings about some things you should not do.) The main reason I might want to use this here is so that I could add some logging along the way - if any of the files can't be deleted, I like to log that as an error rather than ignore it (which is what deleteOnExit() will do). Also this makes it easier to write tests for the method that deletes all the files - it can be a normal method that doesn't have to be run only as a shutdown hook.
"I'm not back." - Bill Harding, Twister
posted 12 years ago
Thanks for revising codes for me. I tested and it indeed works. And the javadoc of my version of JDK doesn't mention the reverse order thing.
Actually I may not only delete files but also need do some other things, and your advice is greatly helpful.
Wish both of you a Merry Christmas and a Happy New Year. [ December 19, 2007: Message edited by: vichy baby ]