开发者

Getting the number of files in a folder in java [duplicate]

This question already has answers here: Counting the number of files in a directory using Java (12 answers) Closed 7 years ago.

I'm making a basic file browser and want to know how to get the number of files in any given directory (necessary for the 开发者_开发知识库for loops that add the files to the tree and table)


From javadocs:

  • http://download.oracle.com/javase/6/docs/api/java/io/File.html

You can use:

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


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


as for 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜