Your code is broken in the way it's looping - you're stopping on the very first iteration, either reporting success or failure. You should be continuing to loop until you find something or run out of items to iterate over.
I would change the general structure so that the last statement in the method is return null;
- so any time you can return a positive result, you do so, but otherwise you just let it fall through. So something like this:
public static File searchFile(File currentFile) {
if (!currentFile.isDirectory()) {
throw new InvalidArgumentException("Starting point must be a directory");
}
for (File file : currentFile.listFiles()) {
if (file.isDirectory()) {
File result = searchFile(file);
if (result != null) {
return result;
}
} else if (file.getName().toLowerCase().endsWith(".sh")) {
return file;
}
}
// Not found anything: return null to indicate failure (in this branch)
return null;
}
(I've removed the call to getParentFile()
and restructured the code for simplicity. Now it will only accept a directory as the starting point, but that simplifies things greatly, and makes much more sense anyway, IMO.)