Sometimes you need to delete files having certain extension within a directory. Two approach are possible, you can either list all files within the directory and check their extension before deletion or list only files having the extension using filename Filter and delete all of them.

This article shows this two approaches:

  1. Using FilenameFilter
  2. Using native java

1- FilenameFilter

JDK 1.1+

Java provides the interface java.io.FilenameFilter to filter filenames. Instances of classes that implement it are used to filter directory listings in the list method of class File.

First thing to do is to create our extension filter that will only accept files ending with certain extension while listing. Below the extension filter :

This filter is used to list files within the directory as below :

2- Using native Java

JDK 1.1+

If you want to list all files within the directory and check their extension before the deletion, below the code :