简体   繁体   English

在Java中的文件夹中查找特定文件

[英]Finding a specific file in a folder in java

I need to find a specific file for example, info.txt in a folder. 我需要在文件夹中找到特定文件,例如info.txt。 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. 我正在使用JDK 1.5。

You can use apache commons-io FileUtils . 您可以使用apache commons-io FileUtils Assuming you want to recursively search for file foo under directory messyfolder : 假设您要递归地在目录messyfolder下搜索文件foo

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. 您可以使用java中的File对象来帮助您。 A couple of the key things you will be using: 您将要使用的几个关键事项:

  • the isDirectory() function. isDirectory()函数。 Fairly self explanatory. 相当自我解释。
  • If the File object is a directory, you will have to use the listFiles() function. 如果File对象是目录,则必须使用listFiles()函数。 Returns an array of file objects which are files AND directories. 返回文件对象的数组,这些文件是文件AND目录。 You just call your recursive function on this array. 您只需在此数组上调用递归函数。
  • You might also want to look into the FilenameFilter interface to help you along. 您可能还需要研究FilenameFilter界面来帮助您。

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. IIRC Java 7具有一些目录遍历实用程序。 You can also use a stack or a queue to walk a directory tree without recursion. 您也可以使用堆栈或队列来遍历目录树而无需递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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