How to delete non-empty Folder in Java

Java supports a function: java.io.File.delete() to delete a File or an empty directory. But with non-empty folders, we need to implement function to delete them. In the tutorial, JavaSampleApproach will show you how to develop a recursive funtion to delete non-empty Folder.

I. Recursive Function
package com.javasampleapproach.deletefolder;

import java.io.File;

public class UtilizeDeleteFolder {
	public static void main(String[] args) {
		// delete folder recursively
		recursiveDeletion(new File("C:\\test"));
	}

	public static void recursiveDeletion(File file) {
		// stop condition
		if (!file.exists())
			return;

		// if non-empty folder, call recursively
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				// recursive function
				recursiveDeletion(f);
			}
		}
		// call delete() function for file and empty directory
		file.delete();
		System.out.println("Deleted folder(file): " + file.getAbsolutePath());
	}
}

II. Output
Deleted folder(file): C:\test\file_test.txt
Deleted folder(file): C:\test\folder_1\3.txt
Deleted folder(file): C:\test\folder_1\folder1.1\1.txt
Deleted folder(file): C:\test\folder_1\folder1.1\2.txt
Deleted folder(file): C:\test\folder_1\folder1.1
Deleted folder(file): C:\test\folder_1
Deleted folder(file): C:\test\folder_2\file_test_1.txt
Deleted folder(file): C:\test\folder_2\file_test_2.txt
Deleted folder(file): C:\test\folder_2
Deleted folder(file): C:\test


By grokonez | February 7, 2017.

Last updated on June 4, 2017.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*