Java如何遍历整个文件的目录呢?
下文笔者讲述遍历整个文件目录的两种方式分享
遍历整个目录的实现思路
方式1:
使用递归的方式遍历目录
方式2:
使用非递归方式遍历目录
递归方式遍历目录
/** * 遍历整个文件目录,递归的 * * @param _dir 指定的目录 * @param method 搜索函数 * @return 搜索结果 * @throws IOException 参数不是目录 */ public static list<Path> walkFileTree(String _dir, Predicate<Path> method) throws IOException { Path dir = Paths.get(_dir); if (!Files.isDirectory(dir)) throw new IOException("参数 [" + _dir + "]不是目录,请指定目录"); List<Path> result = new LinkedList<>(); Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (method.test(file)) result.add(file); return FileVisitResult.CONTINUE; } }); return result; }
非递归方式遍历目录
/**
* 遍历整个目录,非递归的
*
* @param _dir 指定的目录
* @param method 搜索函数
* @return 搜索结果
* @throws IOException 参数不是目录
*/
public static List<Path> walkFile(String _dir, Predicate<Path> method) throws IOException {
Path dir = Paths.get(_dir);
if (!Files.isDirectory(dir))
throw new IOException("参数 :" + _dir + " 不是目录,请指定目录");
List<Path> result = new LinkedList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path e : stream) {
if (method.test(e))
result.add(e);
}
}
return result;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


