两个Java示例向您展示如何列出目录中的文件:
- 对于Java 8,
Files.walk
- 在Java 8之前,创建一个递归循环以列出所有文件。
1. Files.walk
1.1列出所有文件。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.2列出所有文件夹。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.3列出所有以.java
结尾的文件
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".java")).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.4查找文件– HeaderAnalyzer.java
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.contains("HeaderAnalyzer.java"))
.collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
2.经典
在过去,我们可以创建一个递归循环来实现搜索文件功能,如下所示:
2.1列出所有以.java
结尾的文件
package com.mkyong.example;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class JavaExample {
public static void main(String[] args) {
final File folder = new File("C:\\projects");
List<String> result = new ArrayList<>();
search(".*\\.java", folder, result);
for (String s : result) {
System.out.println(s);
}
}
public static void search(final String pattern, final File folder, List<String> result) {
for (final File f : folder.listFiles()) {
if (f.isDirectory()) {
search(pattern, f, result);
}
if (f.isFile()) {
if (f.getName().matches(pattern)) {
result.add(f.getAbsolutePath());
}
}
}
}
}
参考文献
翻译自: https://mkyong.com/java/java-how-to-list-all-files-in-a-directory/