2010-12-06 12 views

答えて

26

あなたは使用することができます。

Javaの7用として
new File("/path/to/folder").listFiles().length 
+1

注 'LISTFILESは()'特定の項目を除外すること。 javadocは次のように述べています* "ディレクトリ自体を表すパス名とそのディレクトリの親ディレクトリは結果に含まれていません" * –

+4

幸いにも、これはほとんどの人の期待にマッチします(例えば 'ls'とは異なります) – Thilo

+2

... listFiles()は配列を割り当て、ディレクトリ内のすべてのファイルに対してFileインスタンスを設定します。ディレクトリに潜在的に膨大な数のファイルがある可能性がある場合は、この方法を使用する場合は注意が必要です。 –

5

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

3

/** 
* 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; 
} 
+0

これは他の回答からどのように優れていますか? – Supuhstar

+1

これは 'NoSuchFieldException'を誤用します。これは、クラスまたはオブジェクトがその中に特定のフィールド(変数/定数)を持たないことを意味しています。 – Supuhstar

+0

異なるバージョンのjdkでは、フォルダ内のファイル数を取得する方法が異なります。 – cane

関連する問題