I am wondering how I would write a recursive program to locate a file in Java that is indicated by a starting path. It should search through a tree for a specified file. If the file is found, the location of the file should be returned. This is what I have so far (not much and still needs basic cleaning up). I need to use these exact methods. I'm mostly confused with what goes in what methods. So I know I need to use:
File f = new File(dirName);
String [] fileList = f.list();
File aFile = new File (dirName + "\\" + fileList[i]);
if (aFile.isDirectory()) {...}
public class FindFile {
If you could help me figure out what method each of those goes in that would be an amazing help!!! I'm just not really understanding the logic of each method. I also have a driver in another class that I need to utilize.
/**
* This constructor accepts the maximum number of files to find.
*/
public FindFile (int maxFiles)
{
}
/**
* The parameters are the target file name to look for and the directory to start in.
* @param target = target file name, dirName = directory to start in
*/
public void directorySearch (String target, String dirName) {
File f = new File(dirName);
String [] fileList = f.list();
File aFile = new File(dirName + "\\" + fileList[i]);
if (aFile.isDirectory()) {
}
else {
}
}
/**
* This accessor returns the number of matching files found.
* @return number of matching files found
*/
public int getCount () {
return -1;
}
/**
* This getter returns the array of file locations, up to maxFiles in size.
* @return array of file locations
*/
public String [] getFiles () {
return new String[] {""};
}
/**
* Prompt the user for max number of files to look for, the directory to start in, and the file name.
* Then, print out the list of found files with the full path name to the file (including starting
* directory). In the event of an exception being thrown, driver catches it and provides an appropriate
* message to the user.
*/
public static void main (String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the max number of files to look for?");
System.out.println("What directory should we start in?");
Systme.out.println("What is the file name?");
}
}
You can use java 8 lambda features like this
try (Stream<Path> walkStream = Files.walk(Paths.get("your search directory"))) {
walkStream.filter(p -> p.toFile().isFile()).forEach(f -> {
if (f.toString().endsWith("file to be searched")) {
System.out.println(f + " found!");
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With