How to Use Filename Filters?
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);
}
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18324)
- How to add BASIC Authentication into HttpURLConnection?(16081)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13988)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)