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

如何在Java中扫描文件夹?

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

如何在Java中扫描文件夹?

不确定要如何表示树?无论如何,这是一个使用递归扫描整个子树的示例。文件和目录是相同的。请注意,File.listFiles()对于非目录返回null。

public static void main(String[] args) {    Collection<File> all = new ArrayList<File>();    addTree(new File("."), all);    System.out.println(all);}static void addTree(File file, Collection<File> all) {    File[] children = file.listFiles();    if (children != null) {        for (File child : children) { all.add(child); addTree(child, all);        }    }}

Java
7提供了一些改进。例如,DirectoryStream一次提供一个结果-
调用者在执行操作之前不再需要等待所有I / O操作完成。这允许增量GUI更新,提前取消等。

static void addTree(Path directory, Collection<Path> all)        throws IOException {    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {        for (Path child : ds) { all.add(child); if (Files.isDirectory(child)) {     addTree(child, all); }        }    }}

请注意,可怕的空返回值已由IOException代替。

Java 7还提供了一个Tree
Walker

static void addTree(Path directory, final Collection<Path> all)        throws IOException {    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {        @Override        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)     throws IOException { all.add(file); return FileVisitResult.CONTINUE;        }    });}


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

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

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