Saturday 4 July 2020

How to Use Filename Filters in java programming languages?

How to Use Filename Filters in java programming languages?

public interface FilenameFilter is an interface that declares single method. Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File, and by the Abstract Window Toolkit's file dialog component.

There is one and only one method in the interface, public boolean accept(File directory, String filename). The method returns true if and only if the filename should be included in the file list; false otherwise.

 

The FilenameFilter is an interface and you must implement this interface in your class. Here is a sample implemeting the method which returns all java files in given directory, the file filter only accepts files ending with ".java".

  public static String[] getFileNames(String dirName) throws IOException{

    File dir = new File(dirName);

    FilenameFilter filter = new FilenameFilter() {
          public boolean accept(File dir, String name) {
            return name.endsWith(".java"));
          }
        };

    return dir.list(filter);
  }
  

0 comments:

Post a Comment