15.1.2 文件过滤器
15.1.2 文件过滤器
File类中使用到FilenameFilter接口的方法
| 方法 | 描述 |
|---|---|
String[] list(FilenameFilter filter) |
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. |
File[] listFiles(FilenameFilter filter) |
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. |
在File类的list()方法中可以接收一个FilenameFilter参数,通过该参数可以只列出符合条件的文件。
这里的FilenameFilter接口和javax.swing.filechooser包下的FileFilter抽象类的功能非常相似,可以把FileFilter当成FilenameFilter的实现类,但可能Sun在设计它们时产生了一些小小遗漏,所以没有让FileFilter实现FilenameFilter接口。
FilenameFilter接口方法
FilenameFilter接口里包含了一个accept方法:
FilenameFilter接口方法 |
描述 |
|---|---|
boolean accept(File dir, String name) |
Tests if a specified file should be included in a file list. |
accept方法将依次对指定File的所有子目录或者文件进行迭代,如果该子目录或者文件经过accept方法处理后返回true,则list()方法会列出该子目录或者文件。
FilenameFilter接口是函数式接口
FilenameFilter接口内只有一个抽象方法,因此该接口也是一个函数式接口,可使用Lambda表达式创建实现该接口的对象
程序示例
1 | import java.io.*; |
上面程序中通过实现accept()方法,来指定哪些文件应该由list()方法列出。
运行上面程序,将看到当前路径下所有的.java文件以及文件夹被列出。
FileFilter接口和FilenameFilter接口的异同
相同点
都用于过滤文件,都只有一个方法,都是函数式接口
方法的参数列表不同
FilenameFilter接口方法 |
描述 |
|---|---|
boolean accept(File dir, String name) |
Tests if a specified file should be included in a file list. |
FileFilter接口方法 |
描述 |
|---|---|
boolean accept(File pathname) |
Tests whether or not the specified abstract pathname should be included in a pathname list. |
范围不同
File类对象使用FilenameFilter既可以过滤得到字符串数组,也可以得到File数组
| 方法 | 描述 |
|---|---|
String[] list(FilenameFilter filter) |
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. |
File[] listFiles(FilenameFilter filter) |
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. |
File类对象使用FileFilter只能得到File数组
| 方法 | 描述 |
|---|---|
File[] listFiles(FileFilter filter) |
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. |
所以FilenameFileter范围比较广一下