Home
Java
Get Directory Size
Updated Jan 26, 2024
Dot Net Perls
Directory size. What is the total size of all files in a folder? In Java we can use the Files.newDirectoryStream method to access all Paths.
Files.newDirectoryStream
With the Path of each file, we can invoke Files.size to get a long value indicating the byte count of the file. This gives us a way to count up all the file sizes.
Files.size
Example. This program introduces a method called getDirectorySize. It is a static method, so we do not need a Program instance to invoke it.
Step 1 We call Program.getDirectorySize with a directory relative to the current working directory we run the Java program in.
Step 2 Get convert the String argument into a path on the file system. This is necessary to call Files.newDirectoryStream.
Step 3 When we call FIles.newDirectoryStream, an exception may be thrown, so we can wrap the call in a try block.
try
Step 4 With a for-loop, we enumerate the Paths returned by newDirectoryStream. On each one, we call Files.size to get the required metadata.
Step 5 We return the total size we computed by summing up all the individual sizes from the files.
import java.io.*; import java.nio.file.*; public class Program { public static long getDirectorySize(String folder) { var sum = 0; // Step 2: get required path. var path = FileSystems.getDefault().getPath(folder); // Step 3: get DirectoryStream from path. try (var stream = Files.newDirectoryStream(path)) { // Step 4: enumerate the Paths and call size on each one, and sum up the sizes. for (Path entry : stream) { var size = Files.size(entry); sum += size; } } catch (IOException exception) { } // Step 5: return the total size. return sum; } public static void main(String[] args) { // Step 1: specify folder name in working directory. var size = Program.getDirectorySize("Movies"); System.out.println("SIZE: " + size); } }
SIZE: 504658
Summary. It is possible to combine multiple methods from the Files class to perform more complex tasks like summing up the size of files in a directory.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 26, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen