[关闭]
@kimo 2016-02-15T02:15:02.000000Z 字数 1103 阅读 1615

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

android笔记


本文摘自 这里

  1. import java.io.File;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.os.Environment;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.Toast;
  9. public class MainDemo extends Activity {
  10. /** Called when the activity is first created. */
  11. private Button button = null;
  12. private File path;
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. button = (Button)findViewById(R.id.mybutton);
  18. //检测SD卡是否存在
  19. if (Environment.getExternalStorageState().equals(
  20. Environment.MEDIA_MOUNTED)) {
  21. path = Environment.getExternalStorageDirectory();
  22. }else{
  23. Toast.makeText(this, "没有SD卡", Toast.LENGTH_LONG).show();
  24. finish();
  25. }
  26. button.setOnClickListener(new OnClickListener() {
  27. @Override
  28. public void onClick(View v) {
  29. // TODO Auto-generated method stub
  30. getAllFiles(path);
  31. }
  32. });
  33. }
  34. // 遍历接收一个文件路径,然后把文件子目录中的所有文件遍历并输出来
  35. private void getAllFiles(File root){
  36. File files[] = root.listFiles();
  37. if(files != null){
  38. for (File f : files){
  39. if(f.isDirectory()){
  40. getAllFiles(f);
  41. }else{
  42. System.out.println(f);
  43. //System.out.println(f.getName);得到文件名
  44. }
  45. }
  46. }
  47. }
  48. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注