Alex Rivera | Logout

Get folder size

Asked 2010-07-02T22:05:41.653
13

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.

Edit
Report

1 Answer

4

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;
}
answered 2010-07-03T01:31:19.157

Your Answer