Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for file in directory with multiple directories

Tags:

java

Here's my goal. I want to be able to pass a parent directory and a filename to a method that searches for that specific file in the directory and any sub-directories. Below is the code I have been working with but can not get it to do exactly what I want. It will find the file I specify but will not return anything.

private static File findFile(File dir, String name) {
    String file     = "";
    File[] dirlist  = dir.listFiles();

    search:
        for(int i = 0; i < dirlist.length; i++) {
            if(dirlist[i].isDirectory()) {
                findFile(dirlist[i], name);
            } else if(dirlist[i].getName().matches(name)) {
                file = dirlist[i].toString();
                break search;
            }
        }

    return new File(file);
}

I know that when the method finds a directory and calls itself it resets the file variable which is where I am storing the found file. So that is why I am getting a blank return. I am not sure how to accomplish this goal or if it's even possible.

like image 873
Lark Avatar asked Sep 03 '09 20:09

Lark


1 Answers

The problem is that you're not returning anything from the recursive call:

if(dirlist[i].isDirectory()) {
    findFile(dirlist[i], name); // <-- here
} else if(dirlist[i].getName().matches(name)) {

I would do the following:

private static File findFile(File dir, String name) {
  File result = null; // no need to store result as String, you're returning File anyway
  File[] dirlist  = dir.listFiles();

  for(int i = 0; i < dirlist.length; i++) { 
    if(dirlist[i].isDirectory()) {
      result = findFile(dirlist[i], name);
      if (result!=null) break; // recursive call found the file; terminate the loop
    } else if(dirlist[i].getName().matches(name)) {
      return dirlist[i]; // found the file; return it
    }
  }
  return result; // will return null if we didn't find anything
}
like image 79
ChssPly76 Avatar answered Jan 25 '23 16:01

ChssPly76