Java如何遍历整个文件的目录呢?

书欣 Java经验 发布时间:2023-07-01 20:53:23 阅读数:16218 1
下文笔者讲述遍历整个文件目录的两种方式分享
遍历整个目录的实现思路
    方式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;
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202307/16882160376956.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者