最简单的Android 遍历SD卡的方法

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

 

posted @ 2017-12-22 14:31  勤能补拙Android  阅读(1431)  评论(0编辑  收藏  举报