There are few ways to get a directory’s size.
Solution 1
[wp_ad_camp_1]
Sum up all the files’ size in the directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 | ... public static long dirSize(File dir) { long size = 0; for (File file : dir.listFiles()) { if (file.isFile()) { size += file.length(); } else { size += dirSize(file); } } return size; } ... |
Solution 2
[wp_ad_camp_2]
Java 7 style
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ... public static long dirSize(String path) throws IOException { AtomicLong dirSize = new AtomicLong(0); Path dir = Paths.get(path); Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { dirSize.addAndGet(attrs.size()); return FileVisitResult.CONTINUE; } }); return dirSize.longValue(); } ... |
Solution 3
[wp_ad_camp_3]
Java 8 style
1 2 3 4 5 6 | ... public static long dirSize(String path) throws IOException { Path p1 = Paths.get(path); return Files.walk(p1).mapToLong(p -> p.toFile().length()).sum(); } ... |