How to get actual size of mounted SD card in Android?

半城伤御伤魂 提交于 2019-12-01 10:40:19
DuKes0mE

Yes, there is a way.

StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long sdAvailSize = (long)stat.getAvailableBlocks()
               * (long)stat.getBlockSize();
//One binary gigabyte equals 1,073,741,824 bytes.
long gigaAvailable = sdAvailSize / 1073741824;

Got that from here: How can I check how much free space an SD card mounted on an Android device has?

Concerning your question about getting total size look here: Getting all the total and available space on Android


Edit:

Marcelo Filho has pointed out that this method is deprecated in API 18 (KitKat).

Google suggests to use getAvailableBlocksLong () and getBlockCountLong () instead. Both methods will return a long value and not a double.

Hint:

Kikiwa has pointed out that the datatype long should be used with these -now deprecated - methods, otherwise you may get negative values if the filesize is too large.

public String[] getSize() throws IOException {
    String memory="";
    Process p = Runtime.getRuntime().exec("df /mnt/sdcard");
    InputStream is =p.getInputStream();
    int by=-1;
    while((by=is.read())!=-1) {
        memory+=new String(new byte[]{(byte)by});
    }
    for (String df:memory.split("/n")) {
        if(df.startsWith("/mnt/sdcard")) {
            String[] par = df.split(" ");
            List<String> pp=new ArrayList<String>();
            for(String pa:par) {
                if(!pa.isEmpty()) {
                    pp.add(pa);
                }
            }
            return pp.toArray(new String[pp.size()]);

        }
    }
    return null;
}

getSize()[0] is /mnt/sdcard. getSize()[1] is size of sd (example 12.0G), getSize()[2] is used, [3] is free, [4] is blksize

Or:

new File("/sdcard/").getFreeSpace() - bytes of free in long
new File("/sdcard/").getTotalSpace() - size of sd
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!