Create Audio FileFilter in Android


What is FileFilter?

FileFilter in Android is an interface in Java which can be used to perform operations on specific files. For example, using FileFilter, you can separate different file types, list the number of specific files or check the type of file and such operations.  The instance of FileFilter can be passed to the listFiles (FileFilter) method of File Class. When it is passed as an instance, it filters specific file types.

Today we are going to write code that will count the number of audio files present in a specific directory.

Step 1: Add permission to manifest

Read External Storage permission is required to read files from phone storage or SD Card. So, we add it using the code given below.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Step 2: Create a Java class implementing the FileFilter Interface

public class AudioFilter implements FileFilter {

 // only want to see the following audio file types
 private String[] extension = {".aac", ".mp3", ".wav", ".ogg", ".midi", ".3gp", ".mp4", ".m4a", ".amr", ".flac"};

 public boolean accept(File pathname) {

 // if we are looking at a directory/file that's not hidden we want to see it so return TRUE
 if (pathname.isDirectory() && !pathname.isHidden()) {
  return true;

 // loops through and determines the extension of all files in the directory
 // returns TRUE to only show the audio files defined in the String[] extension array
 for (String ext : extension) {
   if (pathname.getName().toLowerCase().endsWith(ext)) {
   return true;

 return false;

Array named “extension” indicates the type of Files that will be filtered out.

Step 3: Create another Java class that uses the AudioFilter class

public class MainActivity extends AppCompatActivity {

 protected void onCreate(Bundle savedInstanceState) {
  Log.e("Number of Files: ",countNumberOfFiles("directory path"));

 public static int countNumberOfFiles(String path{ 
  File dir = new File(path);
  File[] files = dir.listFiles(new AudioFilter()); 
  int numberOfFiles = files.length; 
  return numberOfFiles; 

On executing the above code, it will log the number of Audio Files present in the directory specified by “directory path”.

About the author

Editorial Staff

Recommended Host

Siteground hosting Covid19 offers

Top Posts