File class and an example of using FileName filter and listFiles method.
  • This is also an example of using interface FilenameFilter.
  • The class that implements FilenameFilter, must define a method
    • public boolean accept(File dir, String xyz);

import java.io.File;
import java.io.FilenameFilter;
//javac Test_FilenameFilter.java
//java -classpath . Test_FilenameFilter
public class Test_FilenameFilter {
public static void main(String[] args) {
// TODO Auto-generated method stub
File myDir = new File("c:/myjava");
GetFilter select = new GetFilter(myDir,".java");
File[] contents = myDir.listFiles(select);
for (File file : contents) {
System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file"));
}
}
}//end of main class
class GetFilter implements FilenameFilter
{

private String dir;
private String fileExtension;
//the constructor that will receive directory and file extension
public GetFilter( File dir,String fileExtension)
{
this.fileExtension= fileExtension;
System.out.println("costructor gets \t" + "dir : " +dir + " and Ext "+fileExtension);
}
//A class which implements the FilenameFilter interface
//must define this method
public boolean accept(File dir,String filename) {
boolean fileOK = true;
if (dir != null) {
fileOK = filename.endsWith(fileExtension);
}
if (fileExtension != null) {
fileOK = filename.endsWith(fileExtension);
}
return fileOK;
}

}
// end of GetFilter