How to find the amount of free storage (disk space) left on Android?

后端 未结 10 1182
遇见更好的自我
遇见更好的自我 2020-12-02 14:25

I am trying to figure out the available disk space on the Android phone running my application. Is there a way to do this programmatically?

Thanks,

相关标签:
10条回答
  • 2020-12-02 15:09

    Based on @XXX's answer, I've created a gist code snippet that wraps StatFs for easy and simple usage. You can find it here as a GitHub gist.

    0 讨论(0)
  • 2020-12-02 15:10

    Try StatFs.getAvailableBlocks. You'll need to convert the block count to KB with getBlockSize.

    0 讨论(0)
  • 2020-12-02 15:10

    Since blocksize and getAvailableBlocks

    are deprecated

    this code can be use

    note based above answer by user802467

    public long sd_card_free(){
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long availBlocks = stat.getAvailableBlocksLong();
        long blockSize = stat.getBlockSizeLong();
        long free_memory = availBlocks * blockSize;
    
        return free_memory;
    }
    

    we can use getAvailableBlocksLong and getBlockSizeLong

    0 讨论(0)
  • 2020-12-02 15:15
    /**
     * Returns the amount of free memory.
     * @return {@code long} - Free space.
     */
    public long getFreeInternalMemory() {
        return getFreeMemory(Environment.getDataDirectory());
    }
    
    /**
     * Returns the free amount in SDCARD.
     * @return {@code long} - Free space.
     */
    public long getFreeExternalMemory() {
        return getFreeMemory(Environment.getExternalStorageDirectory());
    }
    
    /**
     * Returns the free amount in OS.
     * @return {@code long} - Free space.
     */
    public long getFreeSystemMemory() {
        return getFreeMemory(Environment.getRootDirectory());
    }
    
    /**
     * Returns the free amount in mounted path
     * @param path {@link File} - Mounted path.
     * @return {@code long} - Free space.
     */
    public long getFreeMemory(File path) {
        if ((null != path) && (path.exists()) && (path.isDirectory())) {
            StatFs stats = new StatFs(path.getAbsolutePath());
            return stats.getAvailableBlocksLong() * stats.getBlockSizeLong();
        }
        return -1;
    }
    
    /**
     * Convert bytes to human format.
     * @param totalBytes {@code long} - Total of bytes.
     * @return {@link String} - Converted size.
     */
    public String bytesToHuman(long totalBytes) {
        String[] simbols = new String[] {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"};
        long scale = 1L;
        for (String simbol : simbols) {
            if (totalBytes < (scale * 1024L)) {
                return String.format("%s %s", new DecimalFormat("#.##").format((double)totalBytes / scale), simbol);
            }
            scale *= 1024L;
        }
        return "-1 B";
    }
    
    0 讨论(0)
提交回复
热议问题