Get the file size in android sdk?
The File.length()
method returns the following according to the javadoc:
"The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes."
As you can see, zero can be returned:
- if the file exists but contained zero bytes.
- if the file does not exist, or
- if the file is some OS-specific special file.
My money is on the second case; i.e. that you have the wrong filename / pathname. Try calling File.exists()
on the filename to see what that tells you. The other two cases are possible too, I guess.
(For the record, most /proc/...
files on a Linux-based system also have an apparent file size of zero. And Android is Linux based.)
If you want to get the folder/file size in terms of Kb or Mb then use the following code. It will help in finding the accurate size of your file.
public static String getFolderSizeLabel(File file) { long size = getFolderSize(file) / 1024; // Get size and convert bytes into Kb. if (size >= 1024) { return (size / 1024) + " Mb"; } else { return size + " Kb"; }}
This function will return size in form of bytes:
public static long getFolderSize(File file) { long size = 0; if (file.isDirectory()) { for (File child : file.listFiles()) { size += getFolderSize(child); } } else { size = file.length(); } return size;}