作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我创建了简单的应用程序媒体播放器,我想在设备 android 中获取所有文件 .mp3。在我的代码下面:
File home = new File(String.valueOf(Environment.getExternalStorageDirectory()));
if (home.listFiles().length > 0) {
for (File file : home.listFiles()) {
Log.e("test", file.getPath());
if (file.getName().endsWith(".mp3")) {
Log.e("tesnyae", file.getPath());
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
songsList.add(song);
}
}
} else {}
但是当我使用 Environment.getExternalStorageDirectory()
无法获取设备中的所有 .mp3 时,子文件夹仍然可用,如果我使用特定文件夹无法获取所有文件,是否有解决方案可以自动获取 android 设备中的所有文件 .mp3
最佳答案
正如 Vigor 所提到的,您需要递归地循环访问外部存储的子目录。现在你只是检查外部存储根目录中的文件/目录。这样的事情应该有效:
File home = new File(String.valueOf(Environment.getExternalStorageDirectory()));
checkForMp3Recursive(home);
然后:
private void checkForMp3Recursive(File file) {
if (file.isDirectory()) {
if (file.listFiles().length > 0) {
for (File innerFile : file.listFiles()) {
checkForMp3Recursive(innerFile);
}
}
} else if (file.getName().endsWith(".mp3")) {
Log.e("tesnyae", file.getPath());
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4));
song.put("songPath", file.getPath());
songList.add(song);
}
}
关于android - 如何在android中获取目录设备中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32217172/
我是一名优秀的程序员,十分优秀!