我正在尝试获取用户内部存储中包含MP3文件的所有文件夹的列表。
这是我为此目的而调用的递归函数 -
public void listAllMusicFiles(String pathToDirectory) {
String lastFolderPath = "";
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
lastFolderPath = "";
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
String folderName = inFile.getParentFile().getName();
String folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
//create a new Folder object
Folder currentFolder = new Folder(folderName, folderPath, mp3Count + "");
if (!lastFolderPath.equals(folderPath)) {
Log.d("NEW", folderPath);
lastFolderPath = folderPath;
folderArrayList.add(currentFolder);
} else {
Log.d("OLD", folderPath);
//find a Folder object in folderArrayList where the object's path matches current folderPath
for (Folder folder : folderArrayList) {
String currentPath = folder.getFolder_Path();
if (currentPath.equals(folderPath)) {
//found a match
//update count
folder.setFolder_Song_Count(mp3Count + "");
}
}
}
}
}
}
}
当我在我的设备上运行此代码时,我能够在RecyclerView中列出所需的文件夹,但延迟时间约为6-7秒。
我已经将此任务转移到AsyncTask中,因此我的UIThread不会因为这种密集操作而挂起。
但在提高文件系统性能方面,我完全不知所措。请帮助。谢谢!
答案 0 :(得分:0)
不是将currentFolder存储在ArrayList中,而是在下一步迭代完整列表以查找该文件夹并更新值,您可以像这样使用HashMap
HashMap<String, Folder> folders = new HashMap<>();
public void listAllMusicFiles(String pathToDirectory) {
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
Folder folder;
String folderName, folderPath;
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
folderName = inFile.getParentFile().getName();
folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
if (folders.containsKey(folderPath)) {
folder = folders.get(folderPath);
folder.setFolder_Song_Count(mp3Count + "");
folders.put(folderPath, folder);
} else {
folder = new Folder(folderName, folderPath, mp3Count + "");
folders.put(folderPath, folder);
}
}
}
}
}