We need to implement FilenameFilter class and override accept() method.
Example:
package com.w3spoint;
import java.io.File;
import java.io.FilenameFilter;
public class FilesFilter {
public static void main(String args[]){
File file = new File("D:/Test files/");
String[] files = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.toLowerCase().endsWith(".txt")){
return true;
} else {
return false;
}
}
});
for(String f:files){
System.out.println(f);
}
}
} |
package com.w3spoint; import java.io.File;
import java.io.FilenameFilter; public class FilesFilter {
public static void main(String args[]){
File file = new File("D:/Test files/");
String[] files = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.toLowerCase().endsWith(".txt")){
return true;
} else {
return false;
}
}
});
for(String f:files){
System.out.println(f);
}
}
}
Output:
Download this example.