Sunday, September 11, 2011

Java: how to remove files


I found this at Builders.com
Remove files recursively 
Deleting a directory that contains files is not as uncomplicated as simply creating the File object and invoking delete(). To safely delete a nonempty directory in a platform-independent way, you need a small algorithm, which removes the files and then removes the directories from the bottom of the tree of directories upwards.
To empty a directory of files, you simply loop over the files in the directory and call delete:



This simple method can be reused in a more powerful way to delete a whole directory structure. It should recursively call deleteDirectory whenever it encounters a file that is a directory while looping. The method also should check that the argument passed in is actually a directory. Finally, at the end, it should delete the directory that was passed in.



If you are coding in Java 1.1 or some variants of J2ME/PersonalJava, then there is no File.listFiles method. Instead, you will need to use File.list, which returns an array of Strings, and construct a new File object around each String.

No comments: