how-to

File & Directory

How to list files in directory with filtering

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

import java.io.*;

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() {

     @Override
     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):

test.txt
tns.txt
vallejo.txt

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