如何加速文件存储访问?
问题描述:
我正在尝试获取包含用户内部存储上的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不会由于此密集操作而挂起。
但是当谈到提高文件系统性能时,我完全不知所措。请帮助。谢谢 !
答
而是在一个ArrayList,并在下一步通过完整列表迭代存储currentFolder找到该文件夹和更新的价值,你可以简单地使用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);
}
}
}
}
}
+0
最适合多媒体使用MediaStore。
“listAllMusicFiles(字符串pathToDirectory)”。你在Sting和File之间转换回来和堡垒。使它成为'listAllMusicFiles(文件目录)'。 – greenapps
'folderName = inFile.getParentFile()。getName();'那是'f.getName();'。 – greenapps
当一个目录中有100个mp3文件时,您可以100次迭代数组列表来查看该文件夹是否已经存在。然后你改变那个文件夹的计数一百次。这不是有效的。您应该先计算该文件夹中的文件。当完成该文件夹时,添加名称并计算一次数组。那么你不必检查任何东西。 – greenapps