简体   繁体   中英

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.

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)

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM