File & Directory

How to list files in directory with filtering

For working with files and directories, first add to your application* package:


When you need to go throught files in directory, you can use method File.list(). This method has a parameter of class type FilenameFilter that could perform files filtering.

/* -- go throught directory */

File f = new File( "c:\\" );
String files[] = f.list(
  /* -- filter to .txt extension only */
  new FilenameFilter() {

     public boolean accept(File dir, String name) {                
       return ( name.toLowerCase().endsWith( ".txt" ) );
/* write results */

for ( String s : files ) {
  System.out.println( s );   

The output is (for example):


When you use null value parameter, you will get all files in the directory.