Your recquirement is that input a folder then show the sizes of all files(file including folder) of the folder.
We define the size of a folder is the sum of the size of files in the folder(including sub-folder).
So, the process of the source code is below:
(1) list-up all files of the folder as input.
(2) calculate file-size of listing in (1).
(3) show file-type(FILE OR DIR), the paths of files listing in (1), and file-size calculated in (2).
the source code of (1) and (3) is below:
public static void showFileSizes(File dir) {
File[] files = dir.listFiles(); // (1)
long[] fileSizes = new long[files.length];
for(int i = 0; i < files.length; i++) {
fileSizes[i] = calculateFileSize(file[i]);//invoke the method corresponding to (2).
boolean isDirectory = files[i].isDirectory();
System.out.println(((isDirectory)?"DIR":"FILE") + " - " + files[i].getAbsolutePath() + friendlyFileSize(fileSizes[i]));// as (3)
}
}
the source code of (2) is below:
public static long calculateFileSize(File file) {
long fileSize = 0L;
if(file.isDirectory()) {
File[] children = file.listFiles();
for(File child : children) {
fileSize += calculateFileSize(child);
}
}
else {
fileSize = file.length();
}
return fileSize;
}
The only thing you have to do is invoke showFileSizes method.