在java中获取文件夹中的文件数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4362888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the number of files in a folder in java
提问by Supuhstar
I'm making a basic file browser and want to know how to get the number of files in any given directory (necessary for the for
loops that add the files to the tree and table)
我正在制作一个基本的文件浏览器,想知道如何获取任何给定目录中的文件数(对于for
将文件添加到树和表的循环是必需的)
采纳答案by icyrock.com
From javadocs:
从javadocs:
You can use:
您可以使用:
new File("/path/to/folder").listFiles().length
回答by Ryan Fernandes
new File(<directory path>).listFiles().length
new File(<directory path>).listFiles().length
回答by cane
as for java 7 :
至于java 7:
/**
* Returns amount of files in the folder
*
* @param dir is path to target directory
*
* @throws NotDirectoryException if target {@code dir} is not Directory
* @throws IOException if has some problems on opening DirectoryStream
*/
public static int getFilesCount(Path dir) throws IOException, NotDirectoryException {
int c = 0;
if(Files.isDirectory(dir)) {
try(DirectoryStream<Path> files = Files.newDirectoryStream(dir)) {
for(Path file : files) {
if(Files.isRegularFile(file) || Files.isSymbolicLink(file)) {
// symbolic link also looks like file
c++;
}
}
}
}
else
throw new NotDirectoryException(dir + " is not directory");
return c;
}