android获取手机内部存储空间和外部存储空间

luoyjx · 2015-02-05 19:28 · 2442次阅读

  1. 硬件上的 block size, 应该是"sector size",linux的扇区大小是512byte
  2. 有文件系统的分区的block size, 是"block size",大小不一,可以用工具查看
  3. 没有文件系统的分区的block size,也叫“block size”,大小指的是1024 byte
  4. Kernel buffer cache 的block size, 就是"block size",大部分PC是1024
  5. 磁盘分区的"cylinder size",用fdisk 可以查看。

      我们这里的block size是第二种情况,一般SD卡都是fat32的文件系统,block size是4096.
import java.io.File;

import android.os.Environment;    
import android.os.StatFs;    
    
public class StorageUtil {

    private static final int ERROR = -1;

    /**
     * SDCARD是否存
     */
    public static boolean externalMemoryAvailable() {
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取手机内部剩余存储空间
     * @return
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 获取手机内部总的存储空间
     * @return
     */
    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 获取SDCARD剩余存储空间
     * @return
     */
    public static long getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return availableBlocks * blockSize;
        } else {
            return ERROR;
        }
    }

    /**
     * 获取SDCARD总的存储空间
     * @return
     */
    public static long getTotalExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return totalBlocks * blockSize;
        } else {
            return ERROR;
        }
    }
}
收藏

暂无评论

登录后可以进行评论。没有账号?马上注册