Get file/directory size using Java 7 new IO
How can I get the size of a file or direc开发者_如何学Gotory using the new NIO in java 7?
Use Files.size(Path)
to get the size of a file.
For the size of a directory (meaning the size of all files contained in it), you still need to recurse manually, as far as I know.
Here is a ready to run example that will also skip-and-log directories it can't enter. It uses java.util.concurrent.atomic.AtomicLong
to accumulate state.
public static void main(String[] args) throws IOException {
Path path = Paths.get("c:/");
long size = getSize(path);
System.out.println("size=" + size);
}
static long getSize(Path startPath) throws IOException {
final AtomicLong size = new AtomicLong(0);
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
size.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
// Skip folders that can't be traversed
System.out.println("skipped: " + file + "e=" + exc);
return FileVisitResult.CONTINUE;
}
});
return size.get();
}
MutableLong size = new MutableLong();
Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size.add(attrs.size());
}
}
This would calculate the size of all files in a directory. However, note that all files in the directory need to be regular files, as API specifies size method of BasicFileAttributes:
"The size of files that are not regular files is implementation specific and therefore unspecified."
If you stumble to unregulated file, you ll have either to not include it size, or return some unknown size. You can check if file is regular with
BasicFileAttributes.isRegularFile()
精彩评论