Here is the code which is also attached:
import java.io.File;
public class What033 {
public static void main(String[] args) {
What033 w = new What033();
File dir = new File("D:\\temp");
System.out.println(w.getDirSizeInMegabytes(dir) + "MiB");
}
/**
* It seems that a Directory itself will occupy 4K storage, and this depends
* on different OS, here ignores this issue.
*
* @param dir
* @return
*/
long getDirSize(File dir) {
long size = 0;
if (dir.isFile()) {
size = dir.length();
}
File[] subFiles = dir.listFiles();
for (File file : subFiles) {
if (file.isFile()) {
size += file.length();
} else {
size += this.getDirSize(file);
}
}
return size;
}
long getDirSizeInMegabytes(File dir) {
return this.getDirSize(dir) / 1024 / 1024;
}
}