Share on Google+Share on Google+

Java delete non empty directory

Advertisement
This section demonstrates you how to delete a non empty directory.

Java delete non empty directory

This section demonstrates you how to delete a non empty directory.

It is easy to delete a directory if it is empty by simply calling the built in function delete(). But if the directory is not empty then this method will not delete subdirectories and files of that directory. So it is necessary to recursively delete all the files and subdirectories that are available in the directory.

You can see in the given example, we have created a recursive function deleteDir() that will remove all the files and subdirectories of the given directory. We have called this method in the main function.

Here is the code:

import java.io.*;

public class DeleteNonEmptyDirectory {
	public static void main(String[] argv) throws Exception {
		deleteDir(new File("c:/Hello"));
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}
}

Through the above code, you can delete any non empty directory.

Advertisements

Posted on: April 28, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.