Для проекта, который я делаю, я сделал программу 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";
}
Files.walkFileTree(Path, SimpleFileVisitor<Path>)
сделает все за вас;) - person Marco   schedule 27.05.2013