Exploring
Exploring

Reputation: 3479

Finding a specific file in a folder in java

I need to find a specific file for example, info.txt in a folder. The problem is I do not know under what level the file is. For example, the file can be in a sub-folder or in a sub-folder of a sub-folder.

So this means I have to go through recursion.... Or there is a simple way to complete this task. I am using JDK 1.5.

Upvotes: 0

Views: 122

Answers (3)

You dont have to use recursion, but its a good idea. You can use the File object in java to help you along. A couple of the key things you will be using:

  • the isDirectory() function. Fairly self explanatory.
  • If the File object is a directory, you will have to use the listFiles() function. Returns an array of file objects which are files AND directories. You just call your recursive function on this array.
  • You might also want to look into the FilenameFilter interface to help you along.

A simple mock up of the code would be something like

File findFile(String fileName, File[] files){
    for(File file : files){
        if(file.isDirectory) File f = findFile(fileName, file.listFiles());
        if(f!=null) return f;
        if(file.getName.equals(fileName)) return file;
    }
    return null;
}

Upvotes: 1

gerrytan
gerrytan

Reputation: 41143

You can use apache commons-io FileUtils. Assuming you want to recursively search for file foo under directory messyfolder:

Collection<File> results = FileUtils.listFiles(new File("messyfolder"), 
                                               new NameFileFilter("foo"), 
                                               TrueFileFilter.INSTANCE)

Upvotes: 2

carej
carej

Reputation: 606

IIRC java 7 had some directory walking utils. You can also use a stack or a queue to walk a directory tree without recursion.

Upvotes: 0

Related Questions