I thought about how to check the size of a folder in Java 8. The unit is bytes.
javac foldersize.java
java foldersize folder path
java;foldersize.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class foldersize {
public static void main(String args[]) {
String targetdir;
if (args.length == 0) {
targetdir = ".";
} else {
targetdir = args[0];
}
System.out.println("["+targetdir+"]"+fileSize(targetdir)+"B");
}
public static long fileSize(String path) {
Path folder = Paths.get(path);
long size = 0;
try {
size = Files.walk(folder)
.map(Path::toFile)
.filter(f -> f.isFile())
.mapToLong(f -> f.length())
.sum();
} catch (IOException e) {
e.printStackTrace();
}
return size;
}
}
If there are many files, it will take a long time.
Reference http://www.baeldung.com/java-folder-size
Recommended Posts