我的Android應用程序需要查看默認Camera目錄並獲取在一定時間範圍內創建的JPEG文件的名稱。我目前使用下面的代碼片段來做到這一點。 這個想法是不僅通過「jpg」擴展名過濾文件,而且還使用文件名具有日期/時間的事實。在Android中將所有文件讀入列表的最有效方法
我在線程中運行下面的getImages()函數,以便UI本身不受影響。 我注意到,如果目錄中有很多文件需要一段時間,即使在完成所有這些之後。有更快的算法或Android特定的功能,我可以用來進一步優化它嗎?
private boolean getImages()
{
boolean status=true;
File dir = new File(picPath);
//Optimize file search by setting the common file prefix as a filter
//get the date format used by camera to store files.
String startStr=startTime.format3339(false);
String endStr=endTime.format3339(false);
//Loop through each character of start time
//and compare with end time till a mismatch is found
int len=startStr.length();
int idx=0;
for (idx=0;id < len;idx++)
{
if (startStr.charAt(idx) != endStr.charAt(idx))
{
Log.d(TAG,"breaking at idx "+ idx);
break;
}
}
filterString=endStr.substring(0,idx).replace("T", " ").replace(":",".");
Log.d(TAG,"Filter String" + filterString);
String[] children = dir.list(new JpegFilter());
List matchedFiles = new ArrayList();
Log.d(TAG,dir.getAbsolutePath()+" has "+ children.length+ " files");
int numfiles = children.length;
for(int i=0;i < numfiles;i++)
{
//Get file modify time
File file = new File(picPath+File.separator+children[i]);
// Get the last modification information.
long lastModified = file.lastModified();
if (lastModified > =startTime.toMillis(false)) //If file modified date greater than equals start time
{
Log.d(TAG,"Match! " + children[i]);
if (lastModified < =endTime.toMillis(false))//If file modified date less than equals end time
{
matchedFiles.add(picPath+File.separator+children[i]);
}
else //We are now over the time range, quit loop to save time
{
break; //TODO break out of for loop
}
}
}
if (!matchedFiles.isEmpty()) //If there are images to be processed
{
status=convertToPDF(matchedFiles,pdfFile);
Log.d(TAG,"convertToPDF() returned " + status);
}
return status;
}
這是過濾器類我用
class JpegFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.startsWith(captureJPEG.filterString) && name.endsWith(".jpg"));
}
}
我會看看,但一個完整的文件瀏覽應用程序將是一個有點超必殺的。讓我看看是否有任何技巧可以在那裏找到。 – SidJ 2011-02-07 15:02:16