Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Getting Space Information About the SD CardBack to Android Cookbook Home | Up to Chapter: Data Persistence

Author: Amir Alagic ('Alagic Amir')
In Published Edition? Yes
FormatLanguage: WikiFormat

Getting Space Information About the SD Card

Problem

You want to find out the amount of total and available space on the SD card

Solution

Use StatFs and Enviroment classes from the android.os package to find total and available space on the SD card.

Discussion

Here is code that obtains the information:

StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
double bytesTotal = (long) statFs.getBlockSize() * (long) statFs.getBlockCount();
double megTotal = bytesTotal / 1048576;

To get total space on the SD card use StatFs in the android.os package and as constructor parameter use Environment.getExternalStorageDirectory().getPath().

Then multiply block size with number of blocks on the SD card.

(long) statFs.getBlockSize() * (long) statFs.getBlockCount();

And to get size in megabytes then divide that with 1048576. To get free space on the SD card replace statFs.getBlockCount() with statFs.getAvailableBlocks().

(long) statFs.getBlockSize() * (long) statFs.getAvailableBlocks();

If you want to display the value with two decimal places you can use a DecimalFormat object from java.text.

DecimalFormat twoDecimalForm = new DecimalFormat("#.##");

See Also