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

时间:2025-04-23 07:04:52

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 ;
        }
    }
}