1. Because you need to delete files, you need the following permissions::
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"> </uses-permission>
2. Core code
Copy codeThe Code is as follows: package com. example. deleteyoumi;
Import java. io. File;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. app. Activity;
Import android. view. Menu;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. Toast;
/*
* @ Author: ZhengHaibo
* Web: http://blog.csdn.net/nuptboyzhb
* Mail: zhb931706659@126.com
* 2013-4-28 Nanjing, njupt, China
*/
Public class DeleteYouMiMainActivity extends Activity implements
OnClickListener {
Private Button deleteButton;
Private final static String youmiPathString = "/mnt/sdcard/Android/data/. youmicache/"; // folder path
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_delete_you_mi_main );
DeleteButton = (Button) findViewById (R. id. delete_youmi );
DeleteButton. setOnClickListener (this );
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// Inflate the menu; this adds items to the action bar if it is present.
GetMenuInflater (). inflate (R. menu. delete_you_mi_main, menu );
Return true;
}
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
Switch (v. getId ()){
Case R. id. delete_youmi:
File file = new File (youmiPathString );
DeleteFile (file );
MHandler. sendEmptyMessage (1 );
Break;
Default:
Break;
}
}
Handler mHandler = new Handler (){
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case 0:
Toast. makeText (getApplicationContext (), "the file or folder does not exist", Toast. LENGTH_LONG). show ();
Break;
Case 1:
Toast. makeText (getApplicationContext (), "deleted successfully! ", Toast. LENGTH_LONG). show ();
Break;
Default:
Break;
}
};
};
/**
* Recursively delete files and folders
*
* @ Param file
* Root directory to be deleted
*/
Public void DeleteFile (File file ){
If (file. exists () = false ){
MHandler. sendEmptyMessage (0 );
Return;
} Else {
If (file. isFile ()){
File. delete ();
Return;
}
If (file. isDirectory ()){
File [] childFile = file. listFiles ();
If (childFile = null | childFile. length = 0 ){
File. delete ();
Return;
}
For (File f: childFile ){
DeleteFile (f );
}
File. delete ();
}
}
}
}
3. Expansion
This document uses deletion as an example. Of course, this method can be used to traverse all files in a folder. For example, search for the hosts file.