java:在目录和子目录中根据文件名搜索文件
我需要根据目录树中的名称查找文件。然后显示该文件的路径。我发现了类似的东西,但它根据扩展名进行搜索。谁能帮助我如何根据我的需要重新编写这段代码...谢谢
public class filesFinder {
public static void main(String[] args) {
File root = new File("c:\\test");
try {
String[] extensions = {"txt"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs...thanks
public class filesFinder {
public static void main(String[] args) {
File root = new File("c:\\test");
try {
String[] extensions = {"txt"};
boolean recursive = true;
Collection files = FileUtils.listFiles(root, extensions, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Java 中的递归目录搜索非常简单。
java.io.File
类有一个listFiles()
方法,该方法给出目录的所有File
子目录;您还可以在File
上调用一个isDirectory()
方法来确定是否应该递归搜索特定子项。Recursive directory search in Java is pretty darn easy. The
java.io.File
class has alistFiles()
method that gives all theFile
children of a directory; there's also anisDirectory()
method you call on aFile
to determine whether you should recursively search through a particular child.您可以像这样使用 FileFilter 。
并
像这样调用它
Java 8 Lamda 使这更容易,而不是使用 FileNameFilter,传递 lambda 表达式
You can use FileFilter Like this.
}
And call it like this
Java 8 Lamda make this easier instead of using FileNameFilter, pass lambda expression
我真的不知道 FileUtils 是做什么的,但是将扩展名中的“txt”更改为“yourfile.whatever”怎么样?
I don't really know what FileUtils does, but how about changing "txt" in extenstions to "yourfile.whatever"?
在目录和嵌套子目录中查找文件:
Find File in a Directory and Nested Sub-Directories :