在Java中,你可以通过实现FilenameFilter类并重写accept(File dir, String name) 方法实现文件过滤功能。
在这个例子中,我们向你展示在“c:\folder”路径下列出所有“.txt”格式的文件并删除。
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
|
package com.it161.demo; import java.io.*; public class FileChecker { private static final String FILE_DIR = "c:\folder" ; private static final String FILE_TEXT_EXT = ".txt" ; public static void main(String args[]) { new FileChecker().deleteFile(FILE_DIR,FILE_TEXT_EXT); } public void deleteFile(String folder, String ext){ GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); //list out all the file name with .txt extension String[] list = dir.list(filter); if (list.length == 0 ) return ; File fileDelete; for (String file : list){ String temp = new StringBuffer(FILE_DIR) .append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println( "file : " + temp + " is deleted : " + isdeleted); } } //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)); } } }
|
原创文章,转载请注明出处:http://www.it161.com/article/javaDetail?articleid=140111233238
更多原创内容,请访问:http://www.it161.com/