1.由於需要刪除文件,因此需要如下權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
2.核心代碼 復制代碼 代碼如下:
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:
[email protected] *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/";//文件夾的路徑
@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(), "文件或文件夾不存在", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "刪除成功!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
};
};
/**
* 遞歸刪除文件和文件夾
*
* @param file
* 要刪除的根目錄
*/
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.拓展 本文是以刪除為例。當然,對於遍歷某文件夾下的所有文件均可用這個方法。如搜索.mp3文件等。