JAVA递归思想实现全盘搜索文件系统之基础版
转载自:https://tufeng.xyz/java/25.html(来源:兔峰博客)
今天,我们用java利用递归思想实现全盘检索搜索文件系统,注意是全盘呦,当我们不知道某一文件在哪个地方,甚至不知道到哪个盘符去找时,
用这套程序来查找是不是更方便些呢?
函数解析:
globleSearchFiles(String des_filename):
首先,我们传入需要查找的文件名des_filename;
然后借助File.listRoots()函数列出文件系统的所有盘符文件(C,D,E,F,G盘这些)
然后遍历盘符借助调用搜索文件函数globleSearchFile()
globleSearchFile(String des_filename):
这个函数正是递归思想的具体实现,
dir_file.listFiles()列出该文件夹下的所有文件并放进数组files里面,然后遍历判断:
-
如果file是文件夹,继续调用searchFile函数实现递归搜索 ,返回结果exist,
如果exist为true, 表示找到目标文件,返回true, 整个递归搜索结束 如果exist为false,表示没有找到目标文件,跳过由递归函数继续搜索
-
如果file是文件,则判断file是不是我们要找的文件,
如果是,返回true, 整个递归搜索结束 如果不是我们要找的文件,则跳过,由递归函数继续搜索
-
否则表示该文件夹为空文件夹,返回false, 表示该文件下没有找到
整个搜索过程由C盘到D盘到E盘到…,一直等到目标文件被找到,或者整个文件系统检索结束
实例代码如下,可以测试一下:
import java.io.File;
// author: 守望者
public class Low_SearchFile {
String find_path = null;
public boolean searchFile(String dir_path,String des_fileName) {
File dir_file = new File(dir_path);
File[] files = dir_file.listFiles();
if(files!=null) {
for(File file:files) {
if(file.isDirectory()) {
boolean exist = searchFile(file.getAbsolutePath(),des_fileName);
if(exist) {return true;}
else {continue;}
}
else {
// System.out.println("file: "+file.getAbsolutePath());
// if(file.getName().equals(des_fileName)) {return true;}
String file_name = file.getName();
if(file_name.equals(des_fileName)) {
find_path = file.getAbsolutePath();
return true;
}
} // if is file
} // for
}
return false;
} // list_files
public boolean globleSearchFile(String des_fileName) {
File[] roots = File.listRoots();
for(File file:roots) {
boolean find = searchFile(file.getAbsolutePath(), des_fileName);
if(find) {return true;}
else {continue;}
} // for
return false;
}
public String get_FindPath() {
return find_path;
}
public static void main(String[] args) {
long start_time = System.currentTimeMillis();
System.out.println("start to search...");
Low_SearchFile searchFile = new Low_SearchFile();
boolean find = searchFile.globleSearchFile("wslk_strings.xml");
if(find) {System.out.println("already find, file path :"+searchFile.get_FindPath());}
else {System.out.println("sorry,not find the file");}
System.out.println("用时:"+((System.currentTimeMillis()-start_time))+"毫秒");
// new SearchFile().new SearchThread("G:\\", "ToolTip.html").start();
}
}