File Name Filter
The following example shows how to filter the contents of a given directory
using FilenameFilter . Here we filter out the log files from the given directory.
package com.bethecoder.tutorials.io;
import java.io.File;
import java.io.FilenameFilter;
public class FileNameFilterTest {
/**
* @param args
*/
public static void main ( String [] args ) {
File directory = new File ( "C:\\NEW" ) ;
File [] filesInDir = directory.listFiles ( new LogFileNameFilter ()) ;
System.out.println ( "Directory file listing of " + directory ) ;
for ( int i = 0 ; i < filesInDir.length ; i ++ ) {
System.out.println ( filesInDir [ i ]) ;
}
}
}
class LogFileNameFilter implements FilenameFilter {
@Override
public boolean accept ( File dir, String name ) {
if ( name.toLowerCase () .endsWith ( ".log" )) {
return true ;
}
return false ;
}
}
It gives the following output,
Directory file listing of C:\NEW
C:\NEW\BIOSinfo.log
C:\NEW\IPC.LOG