Get the file size in android sdk?

JavaAndroidFile

Java Problem Overview


I have a problem getting the size of a file. I have the following code:

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

And always length is zero, yes zero.

I am using Android SDK (not sure what version), the code is running inside an Activity, I have created an sdcard.

Perhaps it is a permission issue? Is there anything I am missing?

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

You should use:

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

instead of:

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

Solution 4 - Java

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

Solution 5 - Java

Kotlin Extension Solution

The first thing you should do with the file is confirm that it exists:

val File?.exists get() = this?.exists() ?: false

If you need a File from a String or Uri, try adding these to make working with them more declarative:

fun Uri.asFile(): File = File(toString())

fun String?.asUri(): Uri? {
    try {
        return Uri.parse(this)
    } catch (e: Exception) {
    }
    return null
}

For reading actual filesize, add these somewhere, then call myFile.sizeInMb or whichever you need

val File.size get() = if (!exists()) 0.0 else length().toDouble()
val File.sizeInKb get() = size / 1024
val File.sizeInMb get() = sizeInKb / 1024
val File.sizeInGb get() = sizeInMb / 1024
val File.sizeInTb get() = sizeInGb / 1024

If you'd like to easily display the values as a string, these are simple wrappers. Feel free to customize the default decimals displayed

fun File.sizeStr(): String = size.toString()
fun File.sizeStrInKb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInKb)
fun File.sizeStrInMb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInMb)
fun File.sizeStrInGb(decimals: Int = 0): String = "%.${decimals}f".format(sizeInGb)

fun File.sizeStrWithBytes(): String = sizeStr() + "b"
fun File.sizeStrWithKb(decimals: Int = 0): String = sizeStrInKb(decimals) + "Kb"
fun File.sizeStrWithMb(decimals: Int = 0): String = sizeStrInMb(decimals) + "Mb"
fun File.sizeStrWithGb(decimals: Int = 0): String = sizeStrInGb(decimals) + "Gb"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchinanzioView Question on Stackoverflow
Solution 1 - JavaStephen CView Answer on Stackoverflow
Solution 2 - JavaPir Fahim ShahView Answer on Stackoverflow
Solution 3 - JavaKAMAL VERMAView Answer on Stackoverflow
Solution 4 - JavaKarthikView Answer on Stackoverflow
Solution 5 - JavaGiboltView Answer on Stackoverflow