Reputation: 739
Can someone help me with fixing my problem. I have a function which checks if a file is present in a particular path. the function checks if the filenames match and also the paths also match.(A file with a particular name could be present in multiple locations). Please find below my code.
memberPath is a static variable which contains the relative path. file_Path is a static variable which gets updated when the match has been found.
My problem is the function finds the match but it breaks out of the for-loop comes to return statement but goes back to the for loop. Can someone help me to fix my code so that once the match is found it returns bac to the calling position.
public static String traverse(String path, String filename) {
String filePath = null;
File root = new File(path);
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
traverse(f.getAbsolutePath(), filename);
} else if (f.getName().equalsIgnoreCase(filename) && f.getAbsolutePath().endsWith(memberPath)) {
filePath = f.getAbsolutePath();
file_Path = filePath;
break ;
}
}
return filePath;
}
Upvotes: 2
Views: 183
Reputation: 739
As pointed by baraky, Karthik and JanDvorak, the updated code is:
public String traverse(String path, String filename) {
String filePath = null;
File root = new File(path);
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
return traverse(f.getAbsolutePath(), filename);
} else if (f.getName().equalsIgnoreCase(filename)
&& f.getAbsolutePath().endsWith(memberPath)) {
filePath = f.getAbsolutePath();
file_Path = filePath;
return filePath;
}
}
return filePath;
}
Thanks guys!!
Upvotes: 1
Reputation: 31952
The way recursion works is that the function calls itself. So when your function return
s, it goes back into the for loop, because it is likely the outer function ( the one that called it) called it from the below line
if (f.isDirectory()) {
traverse(f.getAbsolutePath(), filename);
Since this is the case, you need to add the return here as baraky explains, else you will lose the answer that the inner function derives.
Upvotes: 3
Reputation: 19284
Add :
return traverse(f.getAbsolutePath(), filename);
to return the value you get by this call.
As pointed out - you can return the value instead of break.
Upvotes: 6