Get file/directory size using Java 7 new IO

NioJava 7

Nio Problem Overview


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

Nio Solutions


Solution 1 - Nio

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.

Solution 2 - Nio

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();
}

Solution 3 - Nio

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()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclampView Question on Stackoverflow
Solution 1 - NioJoachim SauerView Answer on Stackoverflow
Solution 2 - NioAksel WillgertView Answer on Stackoverflow
Solution 3 - NioIvan SenicView Answer on Stackoverflow