Android遞迴方式刪除某檔案夾下的所有檔案(.mp3檔案等等)

來源:互聯網
上載者:User

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檔案等。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.