For a project I'm doing I made a java program that searches for a file specified by user input.
The code starts searching in a base directory specified by the user (ie: C:). It loops through all the files in this directory checking if the filename matches the search term given by the user, if it does match, the files absolute path is added to a string. If the file is a directory it is added to a list to be dealt with later.
When the base folder is finished being searched it will search/remove the first directory in the list in the same way (adding any directories found to the list once again) and continues until there are no more directories to search. Then displaying the files found to the user.
My question; is there a better way to search for files? Perhaps searching directories immediately instead of adding them to the list? Any advice would be awesome, thanks in advance! Here's my code.
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>)does everything for you ;)