public static void findFile(File allList,String endName,List<File> filenames){
FileFilter filefilter = new ExtensionFileFilter(endName);
// 创建fileArray名字的数组 ,存储allList目录下的所有文件
File[] fileArray= allList.listFiles();
// 如果传进来一个以文件作为对象的allList 返回
if(null==fileArray){
return ;
}
File[] files = null;
if((allList.getAbsolutePath().indexOf("sd")!=-1)||(allList.getAbsolutePath().indexOf("SD")!=-1))
{
files = allList.listFiles(filefilter);
if(files.length>0)
{
System.out.println("目录: "+files[0].getAbsolutePath());
filenames.add(files[0]);//找到所搜索文件,添加到存储器
}
}
// 偏历目录下的文件
for(int i=0;i<fileArray.length;i++){
// 如果是个目录
if(fileArray[i].isDirectory()){
String dir = fileArray[i].getAbsolutePath();
if(dir.length() - dir.replaceAll("/", "").length() > 3)
break;
findFile(fileArray[i].getAbsoluteFile(),endName,filenames); //递归
}
}
}
public static class ExtensionFileFilter implements FileFilter {
private String extension;
public ExtensionFileFilter(String extension)
{
this.extension = extension;
}
public boolean accept(File file)
{
if(file.isDirectory( ))
{
return false;
}
String name = file.getName();// find the last
return name.equals(extension);//搜索特定名称的文件
/*int index = name.lastIndexOf(".");//搜索特定后缀名文件
if(index == -1) {
return false;
}else
if(index == name.length( ) -1)
{
return false;
}
else
{
return this.extension.equals(name.substring(index+1));
}*/
}
}
public static void getpath(){
String dir = "/";
File file = new File(dir);
List<File> filenames = new ArrayList<File>();
findFile(file,"hello_sd.key",filenames);
// File[] files = (File[]) filenames.toArray();
System.out.println("file:="+filenames.get(0));//打印搜索文件,filenames中存储找到的文件信息
}
需求一改,立马就得变换程序,orz,下面是用C实现搜索,无奈还是很笨啊
void FindFile(const char *dirName,char* desFileName, char* desPath)
{
DIR* dir = NULL;
struct dirent *d_ent = NULL;
struct stat sb;
char currfile[1024]={0};
dir = (DIR*)opendir(dirName);
if(dir == NULL)
return;
int i;
while ( (d_ent = readdir(dir))!= NULL )
{
if(strncmp(d_ent->d_name, ".", 1)==0 || strncmp(d_ent -> d_name,"",1) == 0)
continue;
sprintf(currfile,"%s/%s",dirName,d_ent->d_name);
// LOGI("currfile=%s",currfile);
// LOGI("d_ent->d_name = %s, desFileName = %s",d_ent->d_name,desFileName);
stat(currfile, &sb);
// LOGI("sb.st_nlink = %d",sb.st_nlink);
if(S_ISDIR(sb.st_mode))//如果是目录文件,递归调用
{
// LOGI("This is dir");
if(sb.st_nlink>=6)
continue;
FindFile(currfile,desFileName,desPath);
}else if(strcmp(desFileName,d_ent->d_name) == 0)//是普通文件,比较是否是目标文件
{
LOGI("desPath = %s",dirName);
strncpy(desPath,dirName,strlen(dirName) + 1);
break;
}
}
closedir(dir);
}