我希望您检查文件的扩展名以检查它是否是上述代码中的媒体文件
public class ReadAllFilesFromPathActivity extends Activity {
private List<String> myList;
File file;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.mylist);
myList = new ArrayList<String>();
File directory = Environment.getExternalStorageDirectory();
file = new File( directory + "/Test" );
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
if(checkFileExtension( list[i].getName() )
{
myList.add( list[i].getName() );
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
}
}
并添加以下方法来检查扩展。在枚举中添加了扩展
private boolean checkExtension( String fileName ) {
String ext = getFileExtension(fileName);
if ( ext == null) return false;
try {
if ( SupportedFileFormat.valueOf(ext.toUpperCase()) != null ) {
return true;
}
} catch(IllegalArgumentException e) {
return false;
}
return false;
}
public String getFileExtension( String fileName ) {
int i = fileName.lastIndexOf('.');
if (i > 0) {
return fileName.substring(i+1);
} else
return null;
}
和支持的扩展的枚举(你也可以添加你自己的)
public enum SupportedFileFormat
{
_3GP("3gp"),
MP4("mp4"),
M4A("m4a"),
AAC("aac"),
TS("ts"),
FLAC("flac"),
MP3("mp3"),
MID("mid"),
XMF("xmf"),
MXMF("mxmf"),
RTTTL("rtttl"),
RTX("rtx"),
OTA("ota"),
IMY("imy"),
OGG("ogg"),
MKV("mkv"),
WAV("wav");
private String filesuffix;
SupportedFileFormat( String filesuffix ) {
this.filesuffix = filesuffix;
}
public String getFilesuffix() {
return filesuffix;
}
}
这是更多的代码,但可以帮助你