Delete all folders that don’t have specific file type using java

In this tutorial we will see how to delete all the files and folders that don’t match a specific file type.

In the below code we will delete all the files that are not of “.txt” type and all the folders that don’t contain the files of type “.txt”.

package com.programtalk.example;

import java.io.File;

public class DeleteFoldersAndFilesNotSpecificType {
        public static final String type = ".txt";
	
	public static void main(String[] args) {
	 deleteNotMatchingFoldersNFiles("/tmp");	
	}
	
	public static void deleteNotMatchingFoldersNFiles(String directoryName) {
		java.io.File directory = new File(directoryName);

		// get all the files from a directory
		File[] fList = directory.listFiles();
		for (File file : fList) {
			if (file.isFile()) {
				if (!file.getName().endsWith(type)) {
					file.delete();
				}
			} else if (file.isDirectory()) {
				deleteNotMatchingFoldersNFiles(file.getAbsolutePath());
			}
		}
		if(directory.listFiles() ==  null || directory.listFiles().length == 0){
			directory.delete();
		}
	}
	
}
Like this post? Don’t forget to share it!