Java delete non empty directory


 

Java delete non empty directory

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

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.

Ads