Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file/directory size using Java 7 new IO

Tags:

java-7

nio

How can I get the size of a file or directory using the new NIO in java 7?

like image 455
clamp Avatar asked Aug 31 '11 10:08

clamp


3 Answers

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.

like image 141
Joachim Sauer Avatar answered Oct 17 '22 21:10

Joachim Sauer


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();
}
like image 27
Aksel Willgert Avatar answered Oct 17 '22 22:10

Aksel Willgert


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()
like image 5
Ivan Senic Avatar answered Oct 17 '22 23:10

Ivan Senic