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?
Asked
Active
Viewed 2,637 times
2
-
1file size is in bytes so when you need to convert it to MB just divid by 1024 twice. – Mohammad Ersan Feb 11 '13 at 07:24
3 Answers
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.

Jan Heinrich Reimer
- 741
- 10
- 25
-
Note that this snippet returns the file size in KB, not MB. – Jan Heinrich Reimer Jun 14 '18 at 16:49
3
Using File class method public long getTotalSpace()
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?