8

I need to calculate the physical size of a directory. The naive algorithm to do that could be :

public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
    if (file.isFile()) {
        System.out.println(file.getName() + " " + file.length());
        size += file.length();
    }
    else
        size += getFolderSize(file);
}
return size;
}

but how to deal with symbolic links ?

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
user954469
  • 1,053
  • 1
  • 11
  • 12

3 Answers3

1

getCanonicalPath() This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms). http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html

lingceng
  • 2,415
  • 1
  • 18
  • 19
0

My solution to the first question – how to calculate physical size: How can I get the size of a folder on SD card in Android?

And here is solution how to detect symlinks: Java 1.6 - determine symbolic links

Community
  • 1
  • 1
Aleksejs Mjaliks
  • 8,647
  • 6
  • 38
  • 44
-1

You better use the other API to get the file size the API which is relevant to this would be

public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
    if (file.isFile()) {
        System.out.println(file.getName() + " " + file.getTotalSpace());
        size += file.getTotalSpace();
    }
    else
        size += getFolderSize(file);
}
return size;
}
Dinesh Prajapati
  • 9,274
  • 5
  • 30
  • 47
  • 2
    The doc says for getTotalSpace() : "Returns the total size in bytes of the partition containing this path." -> it doesn't return the file size. + It's only available for api level 9 (i have to run on 1.6) – user954469 Nov 22 '11 at 11:11
  • + the symbolic links can create circular reference. – user954469 Nov 22 '11 at 11:12