这是一个FilenameFilter类用法的例子,实现的列举出“c:\folder“路径下所有以“.jpg”扩展名的文件。
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.it161.demo; import java.io.*; public class FindCertainExtension { private static final String FILE_DIR = "c:\folder" ; private static final String FILE_TEXT_EXT = ".jpg" ; public static void main(String args[]) { new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT); } public void listFile(String folder, String ext) { GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); if (dir.isDirectory()== false ){ System.out.println( "Directory does not exists : " + FILE_DIR); return ; } // list out all the file name and filter by the extension String[] list = dir.list(filter); if (list.length == 0 ) { System.out.println( "no files end with : " + ext); return ; } for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); System.out.println( "file : " + temp); } } // inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this .ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } } |
如果你想删除这些文件,请看本文Java I/O之用FilenameFilter实现根据文件扩展名删除文件
原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140111234213
更多原创内容,请访问:http://www.it161.com/