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

后端 未结 10 1208
遇见更好的自我
遇见更好的自我 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: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";
    }
    

提交回复
热议问题