I've looked at Recursively list files in Java but this doesn't seem to solve my problem. I've tried implementing it the way the answers have shown in this question but I my program still doesn't seem to work the way I want it to. It still doesn't "go down" the level if it finds a directory and sends that new directory path as an argument to check if file exists there.
I'm trying to get my class FileFinder to work. Given a filename and a directory to start searching from I want to search and find the file with the filename.
I've created a sort of test directory in /Users/Name/Documents/testing/
.
There is a file called "test.py" in one of the 3 directories under /Documents/testing/
. But my program won't find the file. If I however give the method the proper directory like /Documents/testing/correctDir/
it does find and print the file and it's path.
So I think my problem is when I find a directory the call to fileFinder
doesn't work like it should. Am I dealing with "AbsolutePath" wrong in that line?
Here's the code:
import java.io.*;
public class FileFinder {
String fileFinder(String fileName, String root){
String pathToFile = "";
File rootDir = new File(root);
File[] files = rootDir.listFiles();
for(File f:files){
if(f.isDirectory()){
//System.out.println(f.getAbsolutePath());
fileFinder(fileName,f.getAbsolutePath());
}
else if(f.getName().equals(fileName)){
pathToFile = f.getAbsolutePath();
}
}
return pathToFile;
}
}