2

I have a text file in sd card , I want to get size of text file in mb programatically from my android application. How can I get size of text file in MB programatically?

Milan Shukla
  • 1,602
  • 18
  • 16

3 Answers3

8

Try the below code:

public long fileSizeInKb(String fileName) {
    File file = new File(fileName);
    long fileSize = file.length();
    return fileSize / 1024;                    
}

Let me know if you are still facing any issue.

3

Using File class method public long getTotalSpace()

And public long length()

Like,

File file = new File("/mnt/sdcard/temp.txt");
String size = readableFileSize(file.getTotalSpace()); // file.length() alternate

And method readableFileSize()

public String readableFileSize(long size) {
    if(size <= 0) return "0";
    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
user370305
  • 108,599
  • 23
  • 164
  • 151
  • Be careful when using the sugested `readableFileSize()` method it does not check for the array index, so e.g. `readableFileSize((long) Math.pow(1024, 5))` will throw an `ArrayIndexOutOfBoundsException` – Jan Heinrich Reimer Jun 14 '18 at 16:34
0

you need to open a stream to the file and then check the size like this:

File file=new File(Environment.getExternalStorageDirectory(), "lala.txt");
long size = file.length();

for more on this try reading here: Get the file size in android sdk?

Community
  • 1
  • 1
thepoosh
  • 12,497
  • 15
  • 73
  • 132