gpt4 book ai didi

java - 比创建文件列表更好的文件搜索算法

转载 作者:行者123 更新时间:2023-12-02 06:03:07 24 4
gpt4 key购买 nike

对于我正在做的一个项目,我制作了一个 java 程序来搜索用户输入指定的文件。

代码开始在用户指定的基本目录(即:C:)中搜索。它遍历此目录中的所有文件,检查文件名是否与用户给出的搜索词匹配,如果匹配,则将文件绝对路径添加到字符串中。如果文件是目录,则将其添加到列表中以供稍后处理。

当基本文件夹搜索完成后,它将以相同的方式搜索/删除列表中的第一个目录(再次将找到的任何目录添加到列表中)并继续,直到没有更多目录可供搜索。然后将找到的文件显示给用户。

我的问题;有没有更好的方法来搜索文件?也许立即搜索目录而不是将它们添加到列表中?任何建议都会很棒,在此先感谢!这是我的代码。

public String SearchDir(File directory){
this.directory = directory;
do{
File[] files = this.directory.listFiles();
if(files != null){
for(int i = 0; i < files.length; i++){

// The current file.
File currentFile = files[i];

// The files name without extension and path
// ie C:\Documents and Settings\myfile.file = myfile
String fileName = this .removeExtension(this.removePath(currentFile.getName()));


// Don't search hidden files
if(currentFile.isHidden()){
continue;
}
System.out.println(currentFile.getAbsolutePath());

// Check if the user wanted a narrow search
if(this.narrow){
// Narrow search = check if the file STARTS with the string given.
if(fileName.toLowerCase().startsWith(this.fileName.toLowerCase())){
this.found += currentFile.getAbsolutePath() + '\n';
this.foundXTimes++;
}
}
else{
// Non-Narrow search = check for the given string ANYWHERE in the file name.
if(fileName.toLowerCase().contains(this.fileName.toLowerCase())){
this.found += currentFile.getAbsolutePath() + '\n';
this.foundXTimes++;
}
}

// If the file is a directory add it to the buffer to be searched later.
if(currentFile.isDirectory()){
this.directoriesToSearch.add(currentFile);
}
}

if(!this.directoriesToSearch.isEmpty()){
this.directory = this.directoriesToSearch.remove(0);
}
}
} while(!this.directoriesToSearch.isEmpty());

if(!this.found.equals(""))
return this.found;
else
return "x";
}

最佳答案

有两种算法。深度优先搜索和广度优先搜索。
http://en.wikipedia.org/wiki/Depth-first_search
http://en.wikipedia.org/wiki/Breadth-first_search

对于您的问题,这些算法的时间效率为 O(n)。更好是不可能的。但是你可以构建二叉树。那么你的搜索效率就是O(logn)。但首先,您必须留出时间来构建二叉树。如果您只搜索一个,请不要使用二叉树。

关于java - 比创建文件列表更好的文件搜索算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com