Android 开发工具类 08_SDCardUtils

SD 卡相关的辅助类:

1、判断 SDCard 是否可用;

2、获取 SD 卡路径;

3、获取 SD 卡的剩余容量,单位 byte;

4、获取指定路径所在空间的剩余可用容量字节数,单位byte;

5、获取系统存储路径;

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

 

posted @ 2015-05-28 13:43  壬子木  阅读(191)  评论(0编辑  收藏  举报