Delete files with extension recursively Java

Delete files with extension recursively Java

If you want to delete files with certain extension recursively including folder and sub folder please use below sample program:

  • Sample java program:
package com.javahonk;

import java.io.File;

public class DeleteFilesCurrentAndSubDirectory {

	public static void main(String[] args) {
		
		File folder = new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService");
		File listOfFiles[] = folder.listFiles();
		
		for (File file : listOfFiles) {			
			deleteFilesRecursively(file);
		}
		
	}
	
	private static void deleteFilesRecursively(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()) {
				deleteFilesRecursively(fileList);
			}
		}
		
		String fileName  = file.getName();		
		if (null != file && fileName.endsWith(".java")) {
			Boolean success = (file.delete());
			
			if (success) {
				System.out.println(file.getAbsolutePath()+" deleted successfully");
			}
		}
	}

}
  • Output:

Delete files with extension recursively Java

For more information delete files please refer oracle documentation here

Leave a Reply

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