Do you know how can I get the folder size in Java?
The length() method in the File class only works for files, using that method I always get a size of 0.
Locate the file in Windows File Explorer. Make a right click on it and click on the option "Properties" in the drop-down menu. A window named as "[foldername] Properties" will pop up showing the folder size in "Size" and space occupied on the disk at "Size on disk" boxes respectively.
How to view the file size of a directory. To view the file size of a directory pass the -s option to the du command followed by the folder. This will print a grand total size for the folder to standard output. Along with the -h option a human readable format is possible.
You can use the Get-ChildItem ( gci alias) and Measure-Object ( measure alias) cmdlets to get the sizes of files and folders (including subfolders) in PowerShell.
import java.io.File;
public class GetFolderSize {
int totalFolder = 0;
int totalFile = 0;
public static void main(String args[]) {
String folder = "C:/GetExamples";
try {
GetFolderSize size = new GetFolderSize();
long fileSizeByte = size.getFileSize(new File(folder));
System.out.println("Folder Size: " + fileSizeByte + " Bytes");
System.out.println("Total Number of Folders: "
+ size.getTotalFolder());
System.out.println("Total Number of Files: " + size.getTotalFile());
} catch (Exception e) {}
}
public long getFileSize(File folder) {
totalFolder++;
System.out.println("Folder: " + folder.getName());
long foldersize = 0;
File[] filelist = folder.listFiles();
for (int i = 0; i < filelist.length; i++) {
if (filelist[i].isDirectory()) {
foldersize += getFileSize(filelist[i]);
} else {
totalFile++;
foldersize += filelist[i].length();
}
}
return foldersize;
}
public int getTotalFolder() {
return totalFolder;
}
public int getTotalFile() {
return totalFile;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With