Creating and Using a Custom File Filter in Java
For this latest installment of the Java Basics Series, we’re going to create and use our own custom file filter.
Our example is going to create a filter that takes a year and a month and filters out text files in the format yyyy-MM.txt for the given year and month.
The Custom Filter
Our custom filter is named MonthlyFileFilter and it implements java.io.FileFilter.
In order to specify our year and month, we first define a constructor that takes year and month in the format yyyy and MM. After validating the year and month, the constructor creates a regular expression that will be used for filtering file names.
public MonthlyFileFilter(String year, String month) { if (!year.matches("^(19|20)\\d\\d$")) { throw new IllegalArgumentException(String.format("Invalid year %s. Years must be in format yyyy", year)); } if (!month.matches("1[0-2]|0[1-9]")) { throw new IllegalArgumentException(String.format("Invalid month %s. Months must be in format MM", month)); } fileNameRegex = String.format("%s\\-%s\\.%s", year, month, ALLOWED_EXTENSION); }
Implementing FileFilter requires us to implement the accept method. The accept method takes a java.io.File object and returns a true or false if it’s acceptable to the filter. Our accept method first ensures that our File is a file and not a directory and then matches it against the regular expression created in our constructor.
We’re forcing the path name to lower case so we can match on txt or TXT files.
@Override public boolean accept(File pathname) { boolean accept = false; if (!pathname.isFile()) { return accept; } if (pathname.getName().toLowerCase().matches(fileNameRegex)) { accept = true; } return accept; }
Using the Custom Filter
To use our filter, we create it by passing in a valid year and month. Then we can pass the filter to any method that takes a FileFilter. In our example, we’ll pass it to the listFiles method on a File that was created over our input directory.
MonthlyFileFilter monthlyFileFilter = new MonthlyFileFilter("2019", "02"); File inputDir = new File("input"); for (File filteredFile : inputDir.listFiles(monthlyFileFilter)) { System.out.printf("Filtered out file %s\n", filteredFile.getName()); }
Conclusion
This quick follow up to the Java Basics: File I/O post builds on our understanding of how to work with files, by allowing us to create custom filters for working with directory contents.
The example code is available on GitHub.
One thought on “Java Basics: Custom File Filter”