Directory
sizeWhat is the total size of all files in a folder? In Java we can use the Files.newDirectoryStream
method to access all Paths.
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.
This program introduces a method called getDirectorySize
. It is a static
method, so we do not need a Program
instance to invoke it.
Program.getDirectorySize
with a directory relative to the current working directory we run the Java program in.String
argument into a path on the file system. This is necessary to call Files.newDirectoryStream
.FIles.newDirectoryStream
, an exception may be thrown, so we can wrap the call in a try block.for
-loop, we enumerate the Paths returned by newDirectoryStream
. On each one, we call Files.size
to get the required metadata.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
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.