Home
Java
Get Directory Size
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 26, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.