[英]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: 您将要使用的几个关键事项:
isDirectory()
function. isDirectory()
函数。 Fairly self explanatory. 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. 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.