Reputation: 3479
I need to find a specific file for example, info.txt in a folder. The problem is I do not know under what level the file is. For example, the file can be in a sub-folder or in a sub-folder of a sub-folder.
So this means I have to go through recursion.... Or there is a simple way to complete this task. I am using JDK 1.5.
Upvotes: 0
Views: 122
Reputation: 20139
You dont have to use recursion, but its a good idea. You can use the File
object in java to help you along. A couple of the key things you will be using:
isDirectory()
function. Fairly self explanatory. File
object is a directory, you will have to use the listFiles()
function. Returns an array of file objects which are files AND directories. You just call your recursive function on this array. A simple mock up of the code would be something like
File findFile(String fileName, File[] files){
for(File file : files){
if(file.isDirectory) File f = findFile(fileName, file.listFiles());
if(f!=null) return f;
if(file.getName.equals(fileName)) return file;
}
return null;
}
Upvotes: 1
Reputation: 41143
You can use apache commons-io FileUtils. Assuming you want to recursively search for file foo under directory messyfolder:
Collection<File> results = FileUtils.listFiles(new File("messyfolder"),
new NameFileFilter("foo"),
TrueFileFilter.INSTANCE)
Upvotes: 2
Reputation: 606
IIRC java 7 had some directory walking utils. You can also use a stack or a queue to walk a directory tree without recursion.
Upvotes: 0