File Filter
The following example shows how to filter the contents of a given directory using FileFilter .
Here we filter out the text files from the given directory.
package com.bethecoder.tutorials.io;
import java.io.File;
import java.io.FileFilter;
public class FileFilterTest {
/**
* @param args
*/
public static void main ( String [] args ) {
File directory = new File ( "C:\\NEW" ) ;
File [] filesInDir = directory.listFiles ( new TextFileFilter ()) ;
System.out.println ( "Directory file listing of " + directory ) ;
for ( int i = 0 ; i < filesInDir.length ; i ++ ) {
System.out.println ( filesInDir [ i ]) ;
}
}
}
class TextFileFilter implements FileFilter {
@Override
public boolean accept ( File file ) {
if ( file.getName () .toLowerCase () .endsWith ( ".txt" )) {
return true ;
}
return false ;
}
}
It gives the following output,
Directory file listing of C:\NEW
C:\NEW\file_ops.txt
C:\NEW\Oracle Identity Manager.txt
C:\NEW\readonly_file.txt
C:\NEW\test.txt