Searching...
Wednesday, 11 June 2014

Java FileNameFilter Example to list files with specific name or extension

19:02
Instances of classes that implement java.io.FilenameFilter interface are used to filter file names from a directory. We can list out a directory and filter files based on the name start with, ends with etc.
Here is one example list out the files which are starting with File and extension of .java from the current directory.

Example

package com.vinod.filetest;

import java.io.File;
import java.io.FilenameFilter;

/**
 *@authorvinod.kumaran
 *
 */
public class FileFilterExample {

public static void main(String[] args) {

File currentdir = new File(System.getProperty("user.dir")
+ "/src/main/java/com/vinod/filetest");
File[] listFiles = currentdir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.startsWith("File") && name.endsWith(".java"));
}
});
for (File listFile : listFiles) {
System.out.println(listFile.getName());
}
}

}
Output
FileFilterExample.java
 

0 comments: