Getting the number of files in a folder in java [duplicate]
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;
}
精彩评论