在java中获取文件夹中的文件数量

在java中获取文件夹中的文件数量

问题描述:

我正在制作一个基本的文件浏览器,并且想知道如何获取任意给定目录中的文件数(对于将这些文件添加到树中的for循环是必需的,表)在java中获取文件夹中的文件数量

从的javadoc:

您可以使用:

new File("/path/to/folder").listFiles().length 
+1

注意`listFiles()`不包括某些条目。 javadoc表示*“表示目录本身的路径名和目录的父目录不包含在结果中。”* – 2010-12-06 03:30:35

+4

幸运的是,这符合大多数人的预期(尽管它不同于`ls`) – Thilo 2010-12-06 04:27:16

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; 
}