Java FileNameFilter example to list files with specific extension

If you need to pick up specific extensions from the given directory and you ask yourself how to filter files using Java. Should implement java FilenameFilter class and override accept() method. Then pass object to list() method to get specific file extensions. Java FileNameFilter example will show you all these stuffs.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

packagecom.javabycode.file;

import java.io.File;

import java.io.FilenameFilter;

publicclassFileFilterSample{

publicstaticvoidmain(Stringa[]){

File file=newFile("C:/javabycode/");

String[]files=file.list(newFilenameFilter(){

@Override

publicbooleanaccept(File dir,Stringname){

if(name.toLowerCase().endsWith(".csv")){

returntrue;

}else{

returnfalse;

}

}

});

System.out.println("Folder javabycode stores all CSV files:");

for(Stringfilecsv:files){

System.out.println(filecsv);

}

}

}

Run the java filenamefilter program give the output Directory javabycode stores all CSV files: file.csv filedata.csv