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.
There is a slight error with simply recursively iterating over all subfolders. It is possible on some file systems to create circular directory structures using symbolic links as is demonstrated below:
mkdir -- parents father/son
ln -sf ${PWD}/father father/son
ls father/son/father/son/father/son/father/son/
To guard against this error, you can use the java.io.File#getCanonicalPath method. The code below is a slight modification of a previous answer.
public static long getFileSize(File folder) throws IOException {
return ( getFileSize ( folder , new HashSet < String > ( ) ) ) ;
}
public static long getFileSize(File folder, Set history)
throws IOException {
long foldersize = 0;
File[] filelist = folder.listFiles();
for (int i = 0; i < filelist.length; i++) {
System.err.println("HISTORY");
System.err.println(history);
boolean inHistory = history.contains(filelist[i].getCanonicalPath());
history.add(filelist[i].getCanonicalPath());
if (inHistory) {
// skip it
} else if (filelist[i].isDirectory()) {
foldersize += getFileSize(filelist[i], history);
} else {
foldersize += filelist[i].length();
}
}
return foldersize;
}