Get the file size in android sdk?

Solution 1:

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.)

Solution 2:

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;
}   

Solution 3:

You should use:

File file = new File(Uri.parse("/sdcard/lala.txt").getPath());

instead of:

File file = new File("/sdcard/lala.txt");

Solution 4:

I would suggest you to use the following code instead of hard-coding the path ("/sdcard/lala.txt"):

File file = new File(Environment.getExternalStorageDirectory().getPath() + "/lala.txt");
file.length()