Java FileNameFilter Example to list files with specific name or extension

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
 

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts