栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

更快地获取大目录内容(java.io.File替代品)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

更快地获取大目录内容(java.io.File替代品)

Java
7的

java.nio.file
软件包可用于增强性能。

迭代器

DirectoryStream<T>
接口可用于遍历目录,而无需将其内容预加载到内存中。当旧的API在文件夹中创建一个包含所有文件名的数组时,新方法将在迭代过程中遇到每个文件名(或缓存文件名的有限大小组)时加载它。

要获取表示给定实例的实例

Path
Files.newDirectoryStream(Path)
可以调用static方法。我建议您使用try-with-
resources语句正确关闭流,但是如果不能关闭,请记住在末尾手动进行操作
DirectoryStream<T>.close()

Path folder = Paths.get("...");try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder)) {    for (Path entry : stream) {        // Process the entry    }} catch (IOException ex) {    // An I/O problem has occurred}

筛选器

DirectoryStream.Filter<T>
界面可用于在迭代过程中跳过条目组。

由于它是a

@FunctionalInterface
,从Java
8开始,您可以使用lambda表达式来实现它,从而覆盖
Filter<T>.accept(T)
决定应接受还是过滤给定目录条目的方法。然后,将
Files.newDirectoryStream(Path,DirectoryStream.Filter<? superPath>)
静态方法与新创建的实例一起使用。或者,您可能更喜欢使用
Files.newDirectoryStream(Path,String)
静态方法,该方法可用于简单的文件名匹配。

Path folder = Paths.get("...");try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, "*.txt")) {    for (Path entry : stream) {        // The entry can only be a text file    }} catch (IOException ex) {    // An I/O problem has occurred}

Path folder = Paths.get("...");try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder,        entry -> Files.isDirectory(entry))) {    for (Path entry : stream) {        // The entry can only be a directory    }} catch (IOException ex) {    // An I/O problem has occurred}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号