Java IO Tutorial - Java File.list(FilenameFilter filter)


File.list(FilenameFilter filter) has the following syntax.

public String [] list(FilenameFilter filter)


In the following code shows how to use File.list(FilenameFilter filter) method.

//from  www.j  a  va2s  .co  m

public class Main{
  public static void main(String[] args) {

    File f = new File("c:/test");

    FilenameFilter filter = new MainFilenameFilter("txt");

    // array of files and directory
    String[] paths = f.list(filter);

    // for each name in the path array
    for (String path : paths) {

class MainFilenameFilter implements FilenameFilter {

  String str;

  // constructor takes string argument
  public MainFilenameFilter(String ext) {
    str = "." + ext;

  public boolean accept(File dir, String name) {
    return name.endsWith(str);

The code above generates the following result.