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

来源:互联网 发布:淘宝supreme正品店 编辑:程序博客网 时间:2024/04/30 10:50

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



 

原创粉丝点击