1 package com.xdsjs.save.utils; 2 3 /** 4 * SD卡相关的辅助类 5 * Created by xdsjs on 2015/10/13. 6 */ 7 8 import java.io.File; 9 10 import android.os.Environment; 11 import android.os.StatFs; 12 13 public class SDCardUtils { 14 private SDCardUtils() { 15 /* cannot be instantiated */ 16 throw new UnsupportedOperationException("cannot be instantiated"); 17 } 18 19 /** 20 * 判断SDCard是否可用 21 * 22 * @return 23 */ 24 public static boolean isSDCardEnable() { 25 return Environment.getExternalStorageState().equals( 26 Environment.MEDIA_MOUNTED); 27 28 } 29 30 /** 31 * 获取SD卡路径 32 * 33 * @return 34 */ 35 public static String getSDCardPath() { 36 return Environment.getExternalStorageDirectory().getAbsolutePath() 37 + File.separator; 38 } 39 40 /** 41 * 获取SD卡的剩余容量 单位byte 42 * 43 * @return 44 */ 45 public static long getSDCardAllSize() { 46 if (isSDCardEnable()) { 47 StatFs stat = new StatFs(getSDCardPath()); 48 // 获取空闲的数据块的数量 49 long availableBlocks = stat.getAvailableBlocks(); 50 // 获取单个数据块的大小(byte) 51 long blockSize = stat.getBlockSize(); 52 return blockSize * availableBlocks; 53 } 54 return 0; 55 } 56 57 /** 58 * 获取指定路径所在空间的剩余可用容量字节数,单位byte 59 * 60 * @param filePath 61 * @return 容量字节 SDCard可用空间,内部存储可用空间 62 */ 63 public static long getFreeBytes(String filePath) { 64 // 如果是sd卡的下的路径,则获取sd卡可用容量 65 if (filePath.startsWith(getSDCardPath())) { 66 filePath = getSDCardPath(); 67 } else {// 如果是内部存储的路径,则获取内存存储的可用容量 68 filePath = Environment.getDataDirectory().getAbsolutePath(); 69 } 70 StatFs stat = new StatFs(filePath); 71 long availableBlocks = (long) stat.getAvailableBlocks() - 4; 72 return stat.getBlockSize() * availableBlocks; 73 } 74 75 /** 76 * 获取系统存储路径 77 * 78 * @return 79 */ 80 public static String getRootDirectoryPath() { 81 return Environment.getRootDirectory().getAbsolutePath(); 82 } 83 84 85 }