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.
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.