Android递归方式删除某文件夹下的所有文件(.mp3文件等等)_Android

分享到:
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: 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/";//文件夹的路径
@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文件等。
昵    称:
验证码:

相关文档: