Does the recursion method continue after returning a value?
I am writing a quick Java recursion method that, given the root folder and file name, looks for files for the specified file name.
import Java.io.File;
public static String searchForFile(File currentFolder, String filename)
{
try
{
File[] path = currentFolder.listFiles();
for (int i = 0; i < path.length; i++)
{
if (path[i].isDirectory())
{
System.out.println("Directory: " + path[i].toString());
searchForFile(path[i], filename);
}
else
{
System.out.println("File: " + path[i].toString());
if(path[i].getName().equals(filename))
{
System.out.println("Your file has been found!";
return path[i].toString();
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null; // Omitting this line yields compiling errors, not sure why?
}
public static void main(String[] args)
{
System.out.println("Hello, enter the root folder and file name.");
String rootFolder = "Desktop";
String fileName = "Hello.txt";
File f = new File("C:\\Users\\Me\\" + rootFolder);
searchForFile(f, fileName);
}
The program itself technically works, but it searchForFile()
continues iterating even after the found file is found. For example, I get output like:
File: C:\Users\Me\Desktop\My Stuff\NotHello.txt
**File: C:\Users\Me\Desktop\My Stuff\Hello.txt**
Your file has been found!
File: C:\Users\Me\Desktop\My Stuff\AlsoNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\StillNotHello.txt
File: C:\Users\Me\Desktop\My Stuff\WhyIsThisMethodStillRunning.txt
I'm already scratching my head a little. I thought I return
always exited the method, so why does the recursion continue even after it returns a value? I haven't found any similar questions, so any help would be much appreciated!
(Also, how can I edit the method so that it returns an empty string ""
if the requested file is not found?)
source to share
You return from the innermost call when you found the file. But when you scan a directory, you are not using the return value.
Change this:
searchForFile(path[i], filename);
in
String result = searchForFile(path[i], filename);
if (result != null) {
return result;
}
return null;
at the bottom of your method there is because all methods must return a value. Whether the file is found or not. If the file is not found in the current directory (or one of its subdirectories), you can return null;
indicate that it was not found.
Side suggestion: Use Optional
in Java 8 instead of null
.
source to share