2010-12-06 2 views

ответ

26

От Javadocs:

Вы можете использовать:

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; 
} 
Смежные вопросы