Share this page 

Delete files with a certain extensionTag(s): IO


Define a special FilenameFilter :
import java.io.*;

public class ExtensionFilter implements FilenameFilter {
  private String extension;
  public ExtensionFilter( String extension ) {
    this.extension = extension;             
  }
  
  public boolean accept(File dir, String name) {
    return (name.endsWith(extension));
  }
}
and then
import java.io.*;

public class FileUtils{

  public static void main(String args[]) throws Exception {
    FileUtils.deleteFiles("c:/test/", ".gif");
  }
  
  public static void deleteFiles( String directory, String extension ) {
    ExtensionFilter filter = new ExtensionFilter(extension);
    File dir = new File(directory);

    String[] list = dir.list(filter);
    File file;
    if (list.length == 0) return;

    for (int i = 0; i < list.length; i++) {
      //file = new File(directory + list[i]);
      file = new File(directory, list[i]);
      System.out.print(file + "  deleted : " + file.delete());
    }
   }
  }
}