FileVisitor打印所有目录和目录中包含的文件的大小
import java.io.IOException; /** n o w j a v a . c o m - 时 代 Java 提供 **/ import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; /** * FileVisitor to print the size of all directories and files contained on the directory * passed as an argument to the program, and the accumulated size of everything */ public class FileVisitorDirectorySize { public static void main(String[] args) throws Exception { if (args.length != 1) System.out.println("Use: java FileVisitorDirectorySize <directory>"); Path root = Paths.get(args[0]); CalculateFileSizeVisitor visitor = new CalculateFileSizeVisitor(); Files.walkFileTree(root, visitor); System.out.format("The given directory contains %d files spread in %d directories, occupying %.4f MB in disk", visitor.numFiles, visitor.numDirs, visitor.sizeSum / (1024.0 * 1024));// 来 自 NowJava.com - 时 代 Java } } class CalculateFileSizeVisitor implements FileVisitor<Path> { int numFiles = 0; int numDirs = 0; long sizeSum = 0; @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { System.out.println("[D] " + dir); numDirs++; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { final long size = attrs.size(); System.out.println("[F]\t\t " + file + ". Size of the file: " + size); sizeSum += size; numFiles++; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws