本文研究的是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
62
63
|
public static void main(String[] args) { String filePath = "c:" + File.separator + "b" ; File file = new File(filePath); if (file.exists()) { if (file.isFile()) { deleteFile(filePath); } else { deleteDirectory(filePath); } } else { System.err.println( "指定的目錄或者文件不存在!" ); } } //刪除單個文件或空的文件夾 public static boolean deleteFile(String filePath) { File file = new File(filePath); //如果文件路徑對應的文件存在,并且是一個文件,則直接刪除 if (file.exists() && file.isFile()) { if (file.delete()) { System.err.println( "文件" + filePath + "刪除成功!" ); return true ; } else { System.err.println( "文件" + filePath + "刪除失敗!" ); return false ; } } else { System.err.println( "文件" + filePath + "不存在!" ); return false ; } } //刪除文件夾及里面的文件 public static boolean deleteDirectory (String dir) { if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); //如果dir對應的問件不存在,或者不是一個目錄,則退出 if (!dirFile.exists() || !dirFile.isDirectory()) { System.err.println( "文件夾" + dir + "不存在!" ); return false ; } boolean flag = true ; //刪除問價夾中的所有文件包括子目錄 File[] files = dirFile.listFiles(); for ( int i = 0 ; i < files.length; i++) { //刪除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break ; } } else { deleteDirectory(files[i].getAbsolutePath()); } } //刪除當前目錄 if (dirFile.delete()) { System.err.println( "目錄" + dir + "刪除成功!" ); return true ; } else { return false ; } } |
總結
以上就是本文關于Java編程迭代地刪除文件夾及其下的所有文件實例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/u012843873/article/details/77479850