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;


public class DeleteFoldersAndFilesNotSpecificType {
        public static final String type = ".txt";
	public static void main(String[] args) {
	public static void deleteNotMatchingFoldersNFiles(String directoryName) { 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)) {
			} else if (file.isDirectory()) {
		if(directory.listFiles() ==  null || directory.listFiles().length == 0){
Like this post? Don’t forget to share it!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.