在java中获取文件夹中的文件数量
答
从的javadoc:
您可以使用:
new File("/path/to/folder").listFiles().length
答
new File(<directory path>).listFiles().length
答
如针对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;
}
注意`listFiles()`不包括某些条目。 javadoc表示*“表示目录本身的路径名和目录的父目录不包含在结果中。”* – 2010-12-06 03:30:35
幸运的是,这符合大多数人的预期(尽管它不同于`ls`) – Thilo 2010-12-06 04:27:16