问题
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