Reputation: 1373
This should be easy. This question (Java - Search for files in a directory) seemed to take me 99% of the way to where I needed to be, but that missing 1% is being a real SOB.
I need to find a specific file in a directory and return the full path and filename as a string. If there's more than one matching file, that's fine, I just need the first match.
The code below works inasmuch as it will recursively traverse a directory structure and return all matches -- I can see it happening when I put sysouts into the various parts of the method -- but I can't for the life of me make it stop when it finds a match and return me the value of the match.
I've tried substituting the FOR statement with a WHILE statement controlled by the the value of the foundfile variable as well as half a dozen other approaches but they all come down to the same end; when I find the matching file and set it to the foundfile variable in the "else if" clause, the for loop just keeps on iterating and overwrites the value of the foundfile variable with the "" value on the next loop. I would have thought that calling the setOutput method from within the "if else" clause would have set the value successfully until the list array was empty, but evidently not.
Clearly there is something about recursion and the persistence of parameters that I'm fundamentally misunderstanding. Can anyone illuminate?
package app;
import java.io.*;
import java.util.*;
class FindFile {
public String setOutput(String name, File file, String fileloc) {
String foundfile = fileloc;
File[] list = file.listFiles();
if (list != null)
for (File fil : list) {
if (fil.isDirectory()) {
setOutput(name, fil, foundfile);
} else if (fil.getName().contains(name)) {
foundfile = (fil.getParentFile() + "\\" + fil.getName());
setOutput(name, fil, foundfile);
}
}
return foundfile;
}
public static void main(String[] args) {
FindFile ff = new FindFile();
String thisstring = ff.setOutput(".jar", new File("/Temp/df384b41-198d-4fee-8704-70952d28cbde"), "");
System.out.println("output: " + thisstring);
}
}
Upvotes: 1
Views: 3556
Reputation: 2664
You can return the file path when you find it. No need to check the other files if you are only interested in the first match:
Here is an example (not tested):
public String setOutput(String name, File file) {
File[] list = file.listFiles();
if (list != null) {
for (File fil : list) {
String path = null;
if (fil.isDirectory()) {
path = setOutput(name, fil);
if (path != null) {
return path;
}
} else if (fil.getName().contains(name)) {
path =fil.getAbsolutePath();
if (path != null) {
return path;
}
}
}
}
return null; // nothing found
}
Upvotes: 4