1. Introduction
1.介绍
Java has had functional interfaces before the addition of the informative annotation, @FunctionalInterface. FilenameFilter is one such interface.
在增加信息性注解@FunctionalInterface之前,Java已经有功能接口。FilenameFilter就是这样一个接口。
We’ll be taking a brief look at its usage and understand where it fits in the world of Java today.
我们将简要了解它的用法,并理解它在当今Java世界中的位置。
2. FilenameFilter
2.FilenameFilter
Since this is a functional interface – we have to have exactly one abstract method, and FilenameFilter follows this definition:
由于这是一个功能接口–我们必须正好有一个抽象方法,而FilenameFilter遵循这个定义。
boolean accept(File dir, String name);
3. Usage
3.使用方法
We use FilenameFilter almost exclusively to list all files — that satisfy the specified filter — inside a directory.
我们几乎只使用FilenameFilter来列出一个目录内的所有文件–满足指定的过滤器。
The overloaded list(..) and listFiles(..) methods in java.io.File take an instance of FilenameFilter and return an array of all files that satisfy the filter.
java.io.File中的重载list(.)和listFiles(.)方法接收一个FilenameFilter的实例并返回满足过滤器的所有文件的array。
The following test case filters all the json files in a directory:
下面的测试案例过滤一个目录中的所有json文件。
@Test
public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
FilenameFilter filter = (dir, name) -> name.endsWith(".json");
String[] expectedFiles = { "people.json", "students.json" };
File directory = new File(getClass().getClassLoader()
.getResource("testFolder")
.getFile());
String[] actualFiles = directory.list(filter);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
3.1. FileFilter as BiPredicate
3.1.FileFilter作为BiPredicate
Oracle added more than 40 functional interfaces in Java 8, and unlike legacy interfaces, these are generic. That meant that we could use them for any reference type.
Oracle在Java 8中增加了40多个功能接口,与传统的接口不同,这些接口是通用的。这意味着我们可以将它们用于任何参考类型。
BiPredicate<T, U> was one such interface. Its’ single abstract method has this definition:
BiPredicate<T, U>就是这样一个接口。它的单一抽象方法有这样的定义。
boolean test(T t, U u);
What this means is that FilenameFilter is just a special case of BiPredicate where T is File and U is String.
这意味着FilenameFilter只是BiPredicate的一个特例,其中T是文件,U是String。
4. Conclusion
4.结论
Even though we now have generic Predicate and BiPredicate functional interfaces, we’ll continue to see occurrences of FilenameFilter simply because it has been in use in existing Java libraries.
即使我们现在有了通用的Predicate和BiPredicate功能接口,我们还是会继续看到FilenameFilter的出现,只因为它一直在现有的Java库中使用。
Also, it serves its single purpose well, so there’s no reason to not use it when applicable.
而且,它的单一用途很好,所以没有理由在适用时不使用它。
As always, all the examples are available over on GitHub.
一如既往,所有的例子都可以在GitHub上找到。