文件夹目录中子文件夹的数量

编程入门 行业动态 更新时间:2024-10-28 04:17:07
本文介绍了文件夹目录中子文件夹的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含数据文件( .txt 等)和子文件夹的文件夹。

I have a folder which consists of both datafiles (.txt etc) and subfolders.

在Java中,我该如何完成获取任何指定目录路径中子文件夹的数量的操作?

In Java, how would I accomplish getting the number of subfolders in any specified directory path?

(因此不包括数据文件;仅对子文件夹进行计数)

(so excluding the datafiles; only counting the subfolders)

我已经读过有关计算 .txt 文件数量的信息,但似乎找不到关于仅计算子文件夹的信息。

I have read about counting the number of .txt files but can't seem to find anything about counting subfolders only.

我不知道从哪里开始,但给您一个想法:

I have no idea where to start but to give you an idea:

String directory = "C:\Users\ . \Desktop\ . \workspace\src\testfolder"; int numberOfSubfolders; //what is numberOfSubfolders in testfolder?

感谢所有帮助。

推荐答案

您可以使用 FileFilter 仅列出目录:

You can use FileFilter to list only directories:

File file = new File("/tmp"); File[] files = file.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } }); System.out.println("Folders count: " + files.length);

Java File 类是综合设计模式,因此您必须实际询问实例是否是文件: isFile()或如果它是目录 isDirectory()。

Java File class is an example of the Composite Design Pattern, so you have to actually ask the instance if it's a file: isFile() or if it's a directory isDirectory().

如果您要计数目录,并且正在使用Java8。 Files.find 函数,可以以更简洁的方式(实际上是单行)执行相同的操作:

If you want to count directories, and you're using Java 8. Files.find function, can do the same thing in a more concise manner (practically one-liner):

long count = Files.find( Paths.get("/tmp"), 1, // how deep do we want to descend (path, attributes) -> attributes.isDirectory() ).count() - 1; // '-1' because '/tmp' is also counted in

更多推荐

文件夹目录中子文件夹的数量

本文发布于:2023-10-08 23:56:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   中子   数量   目录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!