读取SD卡中所有MP3文件
想做一个音乐播放器,首先当然要有播放列表啊,通过查资料,暂时先做了个获取SD卡里所有MP3文件名称的小Demo,效果图如下:
1.资源管理器预览,主要是1个Activity和2个布局文件:
2.然后就是代码了
package com.example.sdtxt; 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.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private ListView mListView; private ArrayList name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.mListView); name = new ArrayList(); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File path = Environment.getExternalStorageDirectory(); // 获得SD卡路径 File[] files = path.listFiles();// 读取 getFileName(files); } SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, name, R.layout.sd_list, new String[] { "Name" }, new int[] { R.id.tc_fileName }); mListView.setAdapter(adapter); } private void getFileName(File[] files) { if (files != null)// 先判断目录是否为空,否则会报空指针 { for (File file : files) { if (file.isDirectory()) { getFileName(file.listFiles()); } else { String fileName = file.getName(); if (fileName.endsWith(".mp3")) { HashMap map = new HashMap(); String s = fileName.substring(0, fileName.lastIndexOf(".")); map.put("Name", fileName.substring(0,fileName.lastIndexOf("."))); name.add(map); } } } } } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/mListView" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:id="@+id/tv_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:text="音乐文件:" /> <TextView android:id="@+id/tc_fileName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout>
3.最后注意添上权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
PS:修改下后缀文件名,也可用于查找其他类型文件 。