我正在制作一个基本的文件浏览器,想知道如何获取任何给定目录中的文件数(对于将文件添加到树和表中的for
循环所必需的)
答案 0 :(得分:27)
来自javadocs:
您可以使用:
new File("/path/to/folder").listFiles().length
答案 1 :(得分:5)
new File(<directory path>).listFiles().length
答案 2 :(得分:3)
至于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;
}