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.
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.
Folders generally have a very small "Size", you can think of them as an index.
All the programs that return a "Size" for a folder actually iterate and add up the size of the files.
Iterate over all subfolders in the folder and get the summary size of all files there.
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
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;
}
}
Use apache-commons-io, there's a FileUtils
class with a sizeOfDirectory
methods
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 < String > 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;
}
}