Java filefilter example to list files and directories in a directory

The Java filefilter example shows you how to filter directory using java FileFilter. I create a directoryFilter object that implements the FileFilter interface, then I implement the accept method. The method returns true if the passed parameter is a directory and false if it is not a directory. More information, you saw how we could get the contents of a directory by using a File object’s listFiles() method to get an list of object file. See more detail Filter files using java FilenameFilter

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

27

28

29

packagecom.javabycode.file;

import java.io.File;

import java.io.FileFilter;

import java.io.IOException;

publicclassFileFilterForDirectory{

publicstaticvoidmain(String[]args)throwsIOException{

File current=newFile(".");// set current directory

FileFilter directoryFilter=newFileFilter(){

publicbooleanaccept(File file){

returnfile.isDirectory();

}

};

File[]listFiles=current.listFiles(directoryFilter);

for(Filef:listFiles){

if(f.isDirectory()){// display all children directories in the current one

System.out.print("Children directory: ");

}else{

System.out.print("File:");

}

System.out.println(f.getCanonicalPath());

}

}

}

Here is the result when we run the above program. All children directories of the directory C:projectsworkspaceDemo are displayed.

1

2

3

Children directory:C:\projects\workspace\Demo\.settings

Children directory:C:\projects\workspace\Demo\bin

Children directory:C:\projects\workspace\Demo\src

That’s all on the tutorial Java filefilter example to list files and directories in a directory. Hope you get and practice this idea on your side.