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

给你一囗甜甜゛ 提交于 2019-12-21 10:18:16

问题


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)


回答1:


From javadocs:

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

You can use:

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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4362888/getting-the-number-of-files-in-a-folder-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!