StatFs類
這裏要介紹下StatFs
這個類,StatFs位於android.os包下,功能是:檢索有關文件系統上空間的總體信息。
我們先來看下StatFs都提供了下列方法(廢棄的方法這裏就不列出了):
方法名 | 功能 |
---|---|
getBlockSizeLong | 文件系統上塊的大小(以字節爲單位) |
getBlockCountLong | 文件系統上的塊總數 |
getFreeBlocksLong | 文件系統上可用的塊的總數,包括保留塊(對普通應用程序不可用),大多數應用程序應使用getAvailableBlocksLong方法 |
getFreeBytes | 文件系統上可用的字節數,包括保留的字節數塊(正常應用程序不可用)。大多數應用程序應使用getAvailableBytes方法 |
getAvailableBlocksLong | 文件系統上可用的塊的數目 |
getAvailableBytes | 文件系統上可用的字節數 |
getTotalBytes | 文件系統支持的字節總數 |
StatFs類構造方法中要傳入路徑,通過Os.statvfs(path)返回StructStatVfs對象,所有的方法調用都是調用這個返回對象的。
StructStatVfs類
StructStatVfs類封裝了文件信息
public final class StructStatVfs {
/** 文件系統塊大小 */
public final long f_bsize; /*unsigned long*/
/** 基本文件系統塊大小 */
public final long f_frsize; /*unsigned long*/
/** 總塊計數 */
public final long f_blocks; /*fsblkcnt_t*/
/** 可用塊計數 */
public final long f_bfree; /*fsblkcnt_t*/
/** 非根可用的可用塊計數 */
public final long f_bavail; /*fsblkcnt_t*/
/** 文件總數 */
public final long f_files; /*fsfilcnt_t*/
/** 空閒文件計數 */
public final long f_ffree; /*fsfilcnt_t*/
/** 非根目錄可用的空閒文件計數 */
public final long f_favail; /*fsfilcnt_t*/
/** 文件系統標識 */
public final long f_fsid; /*unsigned long*/
/** Bit mask of ST_* flags. */
public final long f_flag; /*unsigned long*/
/** 最大文件名長度 */
public final long f_namemax; /*unsigned long*/
/**
* Constructs an instance with the given field values.
*/
public StructStatVfs(long f_bsize, long f_frsize, long f_blocks, long f_bfree, long f_bavail,
long f_files, long f_ffree, long f_favail,
long f_fsid, long f_flag, long f_namemax) {
this.f_bsize = f_bsize;
this.f_frsize = f_frsize;
this.f_blocks = f_blocks;
this.f_bfree = f_bfree;
this.f_bavail = f_bavail;
this.f_files = f_files;
this.f_ffree = f_ffree;
this.f_favail = f_favail;
this.f_fsid = f_fsid;
this.f_flag = f_flag;
this.f_namemax = f_namemax;
}
@Override public String toString() {
return Objects.toString(this);
}
}
獲取SD卡全部存儲空間和可用存儲空間
public final class FileUtils {
public static final int BLOCK_SIZE = 1024;
// 獲取SD卡全部存儲空間
public static long getTotalSize() {
File file = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(file.getPath());
//獲得sdcard上 block的總數
long blockCount = statFs.getBlockCountLong();
//獲得sdcard上每個block 的大小
long blockSize = statFs.getBlockSizeLong();
//計算標準大小使用:1024,當然使用1000也可以
return blockCount * blockSize / BLOCK_SIZE / BLOCK_SIZE;
}
// 獲取SD卡可用存儲空間
public static long getAvailableSize() {
File file = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(file.getPath());
//獲得sdcard上 block的總數
long blockCount = statFs.getAvailableBlocksLong();
//獲得sdcard上每個block 的大小
long blockSize = statFs.getBlockSizeLong();
//計算標準大小使用:1024,當然使用1000也可以
return blockCount * blockSize / BLOCK_SIZE / BLOCK_SIZE;
}
}