1.由于需要删除文件,因此需要如下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

2.核心代码


[java]  
   view plain 
   copy 
   
 
   
 
 
1. package com.example.deleteyoumi;  
2.   
3. import java.io.File;  
4.   
5. import android.os.Bundle;  
6. import android.os.Handler;  
7. import android.os.Message;  
8. import android.app.Activity;  
9. import android.view.Menu;  
10. import android.view.View;  
11. import android.view.View.OnClickListener;  
12. import android.widget.Button;  
13. import android.widget.Toast;  
14. /*
15.  *@author: ZhengHaibo  
16.  *web:  
18.  *2013-4-28  Nanjing,njupt,China
19.  */  
20. public class DeleteYouMiMainActivity extends Activity implements  
21.         OnClickListener {  
22. private Button deleteButton;  
23. private final static String youmiPathString = "/mnt/sdcard/Android/data/.youmicache/";//文件夹的路径  
24.   
25. @Override  
26. protected void onCreate(Bundle savedInstanceState) {  
27. super.onCreate(savedInstanceState);  
28.         setContentView(R.layout.activity_delete_you_mi_main);  
29.         deleteButton = (Button) findViewById(R.id.delete_youmi);  
30. this);  
31.     }  
32.   
33. @Override  
34. public boolean onCreateOptionsMenu(Menu menu) {  
35. // Inflate the menu; this adds items to the action bar if it is present.  
36.         getMenuInflater().inflate(R.menu.delete_you_mi_main, menu);  
37. return true;  
38.     }  
39.   
40. @Override  
41. public void onClick(View v) {  
42. // TODO Auto-generated method stub  
43. switch (v.getId()) {  
44. case R.id.delete_youmi:  
45. new File(youmiPathString);  
46.             DeleteFile(file);  
47. 1);  
48. break;  
49. default:  
50. break;  
51.         }  
52.     }  
53. new Handler() {  
54. public void handleMessage(Message msg) {  
55. switch (msg.what) {  
56. case 0:  
57. "文件或文件夹不存在", Toast.LENGTH_LONG).show();  
58. break;  
59. case 1:  
60. "删除成功!", Toast.LENGTH_LONG).show();  
61. break;  
62. default:  
63. break;  
64.             }  
65.         };  
66.     };  
67. /**
68.      * 递归删除文件和文件夹
69.      * 
70.      * @param file
71.      *            要删除的根目录
72.      */  
73. public void DeleteFile(File file) {  
74. if (file.exists() == false) {  
75. 0);  
76. return;  
77. else {  
78. if (file.isFile()) {  
79.                 file.delete();  
80. return;  
81.             }  
82. if (file.isDirectory()) {  
83.                 File[] childFile = file.listFiles();  
84. if (childFile == null || childFile.length == 0) {  
85.                     file.delete();  
86. return;  
87.                 }  
88. for (File f : childFile) {  
89.                     DeleteFile(f);  
90.                 }  
91.                 file.delete();  
92.             }  
93.         }  
94.     }  
95. }


3.拓展

本博客是以删除为例。当然,对于遍历某文件夹下的所有文件均可用这个方法。如搜索.mp3文件等。