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

前端 未结 2 528
庸人自扰
庸人自扰 2021-01-15 17:21

I\'m trying to find a way to find the total size and free space of a mounted SD card on a phone, from my research on SOF and on the Android devs site I was able to find the

相关标签:
2条回答
  • 2021-01-15 17:49
    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
    
    0 讨论(0)
  • 2021-01-15 18:03

    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.

    0 讨论(0)
提交回复
热议问题