How to delete a directory and its descendants at a time? (Syntax with example)
Answers
Answered by
4
Deleting an empty directory is easy in Java, just use delete() method of java.io.Fileclass, but deleting a directory with files is unfortunately not easy. You just can't delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and sub directories inside this folder. This may seem cumbersome, but unfortunately there is no method which can delete directory with files in Java, not even on Java 7 Files and Paths class. So there is two choices, either you write your own method to recursively delete all files and folder before deleting a directory or alternatively you can use an open source utility library like Apache Commons IO which will do this for you. BTW, If you have to do this without using any third party library than you can use the example shown in this tutorial. You know what, I have asked this question couple of times to Java developers and only 3 out of 10 knows that you cannot delete directory with files in Java. I am not surprised because this is the kind of detail which is not obvious. Until you do it, you don't know this. Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder, as shown in first example of this tutorial. Java 7 got much better with files and directory support but there also unfortunately no direct method to delete a directory with files. Though, In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.
Similar questions
Science,
7 months ago
English,
7 months ago
Computer Science,
1 year ago
Chemistry,
1 year ago
Math,
1 year ago