FileVisitor to print the size of all directories and files contained on the directory - Java File Path IO

Java examples for File Path IO:File Visitor

Description

FileVisitor to print the size of all directories and files contained on the directory

Demo Code


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**/*from w w w  . ja v a2  s  .  com*/
 * 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));
    }
}

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 IOException {
        System.err.println("It was not possible to analyze the file: " + file);
        return FileVisitResult.TERMINATE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
}

Related Tutorials