9 Answers
9

This returns the length of the file in bytes or 0 if the file does not exist. There is no built-in way to get the size of a folder, you are going to have to walk the directory tree recursively (using the listFiles() method of a file object that represents a directory) and accumulate the directory size for yourself:

Be careful if you run this in the C: root directory on a Windows machine; there's a system file there which is (according to java.io.File) neither a file nor a directory. You might want to change the else-clause to check that the File is actually a directory.
–
Paul ClaphamJan 27 '10 at 22:50

2

Simple change to check the parameter to see if it is not a directory at the beginning of the method and return the length then the recursion is simpler - just add the call to self in the same method and then this supports passing in a file reference instead of a directory as well.
–
Kevin BrockJan 28 '10 at 7:48