How to delete files with certain extension only

In Java, you can implements the FilenameFilter, override the accept(File dir, String name) method, to perform the file filtering function.

In this example, we show you how to use FilenameFilter to list out all files that are end with “.txt” extension in folder “c:\\folder“, and then delete it.


package com.mkyong.io;

import java.io.*;

public class FileChecker {
	
   private static final String FILE_DIR = "c:\\folder";
   private static final String FILE_TEXT_EXT = ".txt";
	
   public static void main(String args[]) {
	new FileChecker().deleteFile(FILE_DIR,FILE_TEXT_EXT);
   }
	
   public void deleteFile(String folder, String ext){
		
     GenericExtFilter filter = new GenericExtFilter(ext);
     File dir = new File(folder);
	
     //list out all the file name with .txt extension
     String[] list = dir.list(filter);
	     
     if (list.length == 0) return;

     File fileDelete;
	    
     for (String file : list){
   	String temp = new StringBuffer(FILE_DIR)
                      .append(File.separator)
                      .append(file).toString();
    	fileDelete = new File(temp);
    	boolean isdeleted = fileDelete.delete();
    	System.out.println("file : " + temp + " is deleted : " + isdeleted);
     }
   }
  
   //inner class, generic extension filter 
   public class GenericExtFilter implements FilenameFilter {
	
       private String ext;
	
       public GenericExtFilter(String ext) {
         this.ext = ext;             
       }
	       
       public boolean accept(File dir, String name) {
         return (name.endsWith(ext));
       }
    }
}

5 comments on “How to delete files with certain extension only

  1. Don’t mind but this code doesn’t work! there are null pointer exception on multiple lines

    Reply
  2. hi,
    instead of using dir.list(filter) which return list of strings that needs to be reconstruct as a File. use dir.listFile(filter) that returns the list of the files to delete.

    here is the code:

    public void deleteFile(String folder, final String ext) {
    File dir = new File(folder);

    // list out all the file name with .txt extension
    File[] list = dir.listFiles(new FileFilter() {

    @Override
    public boolean accept(File file) {
    return file.isFile() && file.getName().endsWith(ext);
    }
    });

    if (list.length == 0)
    return;

    for (File file : list) {
    boolean isdeleted = file.delete();
    System.out.println(“file : ” + file.getAbsolutePath() + ” is deleted : ” + isdeleted);
    }
    }

    Reply

Leave a Comment

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