您的位置:首页 > 移动开发 > Android开发

android快速遍历目录及查找文件

2012-01-06 23:16 393 查看
java中遍历目录,可以使用递归的方法:

SearchFile(File[] files)
{
for (File file : files)
{
if (file.isDirectory())//若为目录则递归查找
{
SearchFile(file.listFiles());
}
else if (file.isFile())
{
String path = file.getPath();
if (path.endsWith(".gbc"))//查找指定扩展名的文件
{
//do someth
HashMap<String,Object> map;
map = new HashMap<String,Object>();
map.put("ItemImage", R.drawable.img);
map.put("ItemTitle", path);
listItem.add(map);
}
}
}
}

使用:

String path="/sdcard";
File[] files = new File(path).listFiles();
SearchFile(files);


在sdcard中有很多目录和文件时,上述方法非常的慢,可能要经历几分钟才能完成,基本上不能实用。想不出更好的算法,只能是怀疑java太慢了,

改用c来做应该会快很多,于是用NDK试了一下,果然快了很多:

#include<sys/types.h>
#include<dirent.h>
#include<unistd.h>
void ListPath(char* path)
{
DIR * dir;
struct dirent * ptr;
dir =opendir(path);
char currfile[1024]={0};

int len = strlen(path);
if(path[len-1] != '/')
{
path[len] = '/';
path[len+1] = 0;
}

if( dir == NULL)
{
return;
}

while((ptr = readdir(dir))!=NULL)
{
if(strcmp(ptr->d_name, ".")==0
||strcmp(ptr->d_name,"..")==0)
continue;
sprintf(currfile,"%s%s",path,ptr->d_name);
if (ptr->d_type==8)//普通文件
{
char *p=ptr->d_name + strlen(ptr->d_name)-4;
if (strcmp(p,".gbc")==0)
{
strcpy(romPaths[romCnt], currfile);//把文件路径保存起来
romCnt++;
}
}
else if (ptr->d_type==4)//目录
{
ListPath(currfile);
}
}
closedir(dir);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: