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