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

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);
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值