gpt4 book ai didi

android - 如何在android中获取目录设备中的文件?

转载 作者:搜寻专家 更新时间:2023-11-01 08:41:26 25 4
gpt4 key购买 nike

我创建了简单的应用程序媒体播放器,我想在设备 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com