Android讀取SD卡下面所有的TXT文件名,listView顯示出來。
- 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);
- }
- }
- }
- }
- }
- }