How to delete a directory containing multiple files and sub directories in Java using recursion?
How to delete a directory containing multiple files and sub directories in Java using recursion?
This article is part of a tutorial.
Tutorial Index page - Java File and Directory Deletion
Program Requirements
To begin with lets define the requirements:
Given a directory, delete the directory and all its contents in one go. The directory may contain
- multiple files
- multiple sub directories which further might contain sub directories or files.
Background
J2SE development kit provides the right classes to satisfy our needs. We have already discussed how a single file can be deleted in a directory using Java in one our articles How to delete a file using Java
All we need for our current requirements is to perform the delete operation recursively until all the contents are deleted. As a directory cannot be deleted if not empty, we delete its content first and when the directory becomes empty, the directory can also be deleted.
Implementation Algorithm
1. Create a file instance with the given file path 2. If directory then 2.a. list all its contents 2.b. For each content (File/Subdirectory) 2.b.i. repeat the process from 1 3. else delete the file
Java Implementation
The beauty of Java is that you can write a single method and call it within itself recursively until the entire directory is deleted. All you will need is this single method defined below.
public static boolean deleteFile(String sFilePath) { File oFile = new File(sFilePath); if(oFile.isDirectory()) { File[] aFiles = oFile.listFiles(); for(File oFileCur: aFiles) { deleteFile(oFileCur.getAbsolutePath()); } } return oFile.delete(); }
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
