Delete Directory Java

Delete Directory Java

Below is sample java program which will delete directory. Please be aware until you empty all content of the directory you can not delete it so for this we will use method recursion to empty directory and delete it when its empty.

  • Sample java program:
package com.javahonk;

import java.io.File;

public class DeleteDirectory {	

	public static void main(String[] args) {
		
		String delteFolderPath = "C:\\JavaHonk\\zip\\SpringMVCRESTFulService";		
		deleteFolderRecursively(new File(delteFolderPath));
		System.out.println("Folder deleted successfully");
		
	}

	private static void deleteFolderRecursively(File file) {

		if (!file.exists()){
			System.err.format("%s: no such" + " file or directory%n", file.getAbsolutePath());
			return;
		}
		
		if (file.isDirectory()) {
			for (File fileList : file.listFiles()) {
				deleteFolderRecursively(fileList);
			}
		}
		System.out.println("Deleted file name: "+file.getAbsolutePath());
		file.delete();
	}
}
  • Output:

Delete Directory Java

  • For more information about deleting file or directory please refer oracle documentation here 

Leave a Reply

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