Android 最简单的SD卡文件遍历程序

时间:2021-06-29 15:02:26
package com.wenhao.test.sddemo;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class MainDemo extends Activity {
/** Called when the activity is first created. */ private Button button = null;
private File path; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); button = (Button)findViewById(R.id.mybutton); //检测SD卡是否存在
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory();
}else{
Toast.makeText(this, "没有SD卡", Toast.LENGTH_LONG).show();
finish();
} button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
getAllFiles(path);
}
}); } // 遍历接收一个文件路径,然后把文件子目录中的所有文件遍历并输出来
private void getAllFiles(File root){
File files[] = root.listFiles();
if(files != null){
for (File f : files){
if(f.isDirectory()){
getAllFiles(f);
}else{
System.out.println(f);
}
}
}
} }