2010-12-06 89 views

回答

26

從的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

5

new File(<directory path>).listFiles().length

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; 
} 
相關問題