This is my preferred solution:
public static Long getFileSize(String path) {
return getFileSize(new File(path));
}
public static Long getFileSize(File file) {
return (!file.isFile()) ? -1L : file.length();
}
Note that it is returning -1L rather than 0L, to allow the caller to distinguish between an empty file, and a "file" whose length cannot be determined for some reason. The file.length()
will return zero in some cases where you don't have a zero length file; e.g.
- when the
file
does not exist
- when the
file
is a directory
- when the
file
is a special file (e.g. device file, pipe, etc) and the OS cannot determine its length.
The file.isFile()
call deals with these cases. However, it is debatable whether the method(s) should return -1L
or throw an exception. The answer to this debate turns on whether the -1L
cases are "normal" or "exceptional", and that can only be determined with reference to the contexts in which the method is designed to be used,