java 如何找到文件
查找文件的方法
使用 java.io.File 类或 java.nio.file.Path 接口可以查找文件。以下是几种常见的方法。
使用 File 类查找文件

File file = new File("path/to/file.txt");
if (file.exists()) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
使用 Files 类(NIO)检查文件是否存在
Path path = Paths.get("path/to/file.txt");
if (Files.exists(path)) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在");
}
递归查找目录下的所有文件

public static void listFiles(String directoryPath) {
File directory = new File(directoryPath);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
System.out.println("文件: " + file.getAbsolutePath());
} else if (file.isDirectory()) {
listFiles(file.getAbsolutePath());
}
}
}
}
使用 Files.walk 遍历目录(Java 8+)
Path startPath = Paths.get("path/to/directory");
try (Stream<Path> stream = Files.walk(startPath)) {
stream.filter(Files::isRegularFile)
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
按文件名模式查找文件
File dir = new File("path/to/directory");
File[] matchingFiles = dir.listFiles((dir1, name) -> name.startsWith("prefix") && name.endsWith(".txt"));
if (matchingFiles != null) {
for (File file : matchingFiles) {
System.out.println(file.getName());
}
}
注意事项
- 路径可以是相对路径或绝对路径。
- 使用
try-catch处理可能的IOException。 - NIO(
Path和Files)比传统的File类更灵活,推荐在新代码中使用。






