If you need to pick up specific extensions from the given directory and you ask yourself how to filter files using Java. Should implement java FilenameFilter class and override accept() method. Then pass object to list() method to get specific file extensions. Java FileNameFilter example will show you all these stuffs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.javabycode.file; import java.io.File; import java.io.FilenameFilter; public class FileFilterSample { public static void main(String a[]) { File file = new File("C:/javabycode/"); String[] files = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.toLowerCase().endsWith(".csv")) { return true; } else { return false; } } }); System.out.println("Folder javabycode stores all CSV files:"); for (String filecsv : files) { System.out.println(filecsv); } } } |
Run the java filenamefilter program give the output
Directory javabycode stores all CSV files:
file.csv
filedata.csv
This sample seems to be simple but it is useful when you want to filter files in a directory. One other good example is How to filter directory using java.io.FileFilter.
Happy leanring!