本文實例講述了Java實現的模糊匹配某文件夾下的文件并刪除功能。分享給大家供大家參考,具體如下:
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
54
55
56
57
58
59
60
61
|
package com.wyebd.gis; import java.io.File; /** * @Title: DelFiles.java * @Package com.wyebd.gis * @Description: * @author lisr * @date Mar 7, 2012 5:36:03 PM * @version V1.0 */ public class DelFiles { /** * @Title: main * @Description: * @param args * @return void * @author lisr * @date Mar 7, 2012 5:36:04 PM * @throws */ //用以模糊刪除頭部為str的文件 public static boolean delFilesByPath(String path,String str){ //參數說明---------path:要刪除的文件的文件夾的路徑---------str:要匹配的字符串的頭 boolean b= false ; File file = new File(path); File[] tempFile = file.listFiles(); for ( int i = 0 ; i < tempFile.length; i++){ if (tempFile[i].getName().startsWith(str)||tempFile[i].getName().endsWith(str)){ System.out.println( "將被刪除的文件名:" +tempFile[i].getName()); boolean del=deleteFile(path+tempFile[i].getName()); if (del){ System.out.println( "文件" +tempFile[i].getName()+ "刪除成功" ); b= true ; } else { System.out.println( "文件" +tempFile[i].getName()+ "刪除失敗" ); } } } return b; } private static boolean deleteFile(String path){ System.out.println(path); boolean del= false ; File file= new File(path); if (file.isFile()){ file.delete(); del= true ; } return del; } public static void main(String[] args) { // TODO Auto-generated method stub String path= "D:/temp/" ; String str= "44_" ; if (delFilesByPath(path,str)){ System.out.println(path+ "中包含" +str+ "的文件已經全部刪除成功!" ); } else { System.out.println(path+ "中包含" +str+ "的文件已經刪除失敗或該文件夾下不存在這類文件!" ); } } } |
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
|
package com.wyebd.gis; import java.io.File; /** * @Title: DelFiles.java * @Package com.wyebd.gis * @Description: * @author lisr * @date Mar 7, 2012 5:36:03 PM * @version V1.0 */ public class DelFiles { /** * @Title: main * @Description: * @param args * @return void * @author lisr * @date Mar 7, 2012 5:36:04 PM * @throws */ //用以模糊刪除頭部為str的文件 public static boolean delFilesByPath(String path,String str){ //參數說明---------path:要刪除的文件的文件夾的路徑---------str:要匹配的字符串的頭 boolean b= false ; File file = new File(path); File[] tempFile = file.listFiles(); for ( int i = 0 ; i < tempFile.length; i++){ if (tempFile[i].getName().startsWith(str)||tempFile[i].getName().endsWith(str)){ tempFile[i].delete(); b= true ; } } return b; } public static void main(String[] args) { String path= "D:/temp/" ; String str= "44_" ; if (delFilesByPath(path,str)){ System.out.println(path+ "中包含" +str+ "的文件已經全部刪除成功!" ); } else { System.out.println(path+ "中包含" +str+ "的文件已經刪除失敗或該文件夾下不存在這類文件!" ); } } } |
個人認為:如果要實現更高級的這種模糊匹配,只需要用String的indexOf()
方法,凡是含有這個字符串的文件,都一并刪除!
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/lishirong/article/details/41674511