import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class FindFirstExample {
public static void main(String[] args) {
Path startingDir = Paths.get(".");
try {
// 使用 Files.find 方法查找第一个匹配的文件
Path firstMatch = Files.find(startingDir, Integer.MAX_VALUE,
(path, attrs) -> path.toString().endsWith(".java"))
.findFirst()
.orElse(null);
if (firstMatch != null) {
System.out.println("First .java file found: " + firstMatch);
} else {
System.out.println("No .java file found.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
java.nio.file.* 和 java.nio.file.attribute.BasicFileAttributes,这些是用于文件系统操作的类。FindFirstExample 的类,并在其中定义 main 方法。Paths.get(".") 获取当前目录作为起始点。Files.find 方法:这个方法递归地遍历文件树,查找符合条件的文件。这里我们查找以 .java 结尾的文件。Integer.MAX_VALUE 表示不限制搜索深度。(path, attrs) -> path.toString().endsWith(".java") 是一个 Lambda 表达式,表示只匹配文件名以 .java 结尾的文件。findFirst() 方法获取第一个匹配的文件路径。希望这段代码和解释对你有帮助!
上一篇:java中map
下一篇:java基础类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站