Android读取SD卡下面所有的TXT文件名 listView显示出来

来源:http://www.linuxidc.com/Linux/2011-12/49966.htm

package your.txtsdka;  

import java.io.File;  
import java.util.ArrayList;  
import java.util.HashMap;  

import android.app.Activity;  
import android.os.Bundle;  
import android.os.Environment;  
import android.util.Log;  
import android.widget.ListView;  
import android.widget.SimpleAdapter;  

public class Txt_sdkaActivity extends Activity {  
    private ListView lv;  
    ArrayList name;  

    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        lv = (ListView) findViewById(R.id.lv);  
        name = new ArrayList();  
        if (Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED)) {  
            File path = Environment.getExternalStorageDirectory();// 获得SD卡路径   
            // File path = new File("/mnt/sdcard/");   
            File[] files = path.listFiles();// 读取   
            getFileName(files);  
        }  
        SimpleAdapter adapter = new SimpleAdapter(this, name, R.layout.sd_list,  
                new String[] { "Name" }, new int[] { R.id.txt_tv });  
        lv.setAdapter(adapter);  
        for (int i = 0; i < name.size(); i++) {  
            Log.i("zeng", "list.  name:  " + name.get(i));  
        }  
    }  

    private void getFileName(File[] files) {  
        if (files != null) {// 先判断目录是否为空,否则会报空指针   
            for (File file : files) {  
                if (file.isDirectory()) {  
                    Log.i("zeng", "若是文件目录。继续读1" + file.getName().toString()  
                            + file.getPath().toString());  

                    getFileName(file.listFiles());  
                    Log.i("zeng", "若是文件目录。继续读2" + file.getName().toString()  
                            + file.getPath().toString());  
                } else {  
                    String fileName = file.getName();  
                    if (fileName.endsWith(".txt")) {  
                        HashMap map = new HashMap();  
                        String s = fileName.substring(0,  
                                fileName.lastIndexOf(".")).toString();  
                        Log.i("zeng", "文件名txt::   " + s);  
                        map.put("Name", fileName.substring(0,  
                                fileName.lastIndexOf(".")));  
                        name.add(map);  
                    }  
                }  
            }  
        }  
    }  
}  

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值