内部存储
1、总大小
java
public static long getInternalStorageSize(Context context) {
File filesDir = context.getFilesDir();
return filesDir.getTotalSpace();
}
2、可用空间大小
java
public static long getFreeSpace(Context context) {
File filesDir = context.getFilesDir();
return filesDir.getFreeSpace();
}
扩展TF卡
1、总大小
java
public static long getExternalStorageSize(Context context) {
StorageManager storageManager = context.getSystemService(StorageManager.class);
for (StorageVolume volume : storageManager.getStorageVolumes()) {
if (volume.isRemovable()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
File directory = volume.getDirectory();
LogUtils.i("fileUtils", "directory = " + directory.getAbsolutePath());
LogUtils.i("fileUtils", "directory = " + directory.getTotalSpace());
return directory.getTotalSpace();
}
} else {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
File directory = volume.getDirectory();
LogUtils.i("fileUtils", "false directory = " + directory.getAbsolutePath());
LogUtils.i("fileUtils", "false directory = " + directory.getTotalSpace());
}
}
}
return 0;
}
2、可用空间大小
java
public static long getExternalStorageFreeSize(Context context) {
StorageManager storageManager = context.getSystemService(StorageManager.class);
for (StorageVolume volume : storageManager.getStorageVolumes()) {
if (volume.isRemovable()) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
File directory = volume.getDirectory();
LogUtils.i("fileUtils", "directory = " + directory.getAbsolutePath());
LogUtils.i("fileUtils", "free = " + directory.getFreeSpace());
return directory.getFreeSpace();
}
} else {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
File directory = volume.getDirectory();
LogUtils.i("fileUtils", "false directory = " + directory.getAbsolutePath());
LogUtils.i("fileUtils", "false directory = " + directory.getTotalSpace());
}
}
}
return 0;
}
单位转换
java
public static String storageSizeConversion(long size) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (size < 1024) {
fileSizeString = df.format((double) size) + "B";
} else if (size < 1048576) {
fileSizeString = df.format((double) size / 1024) + "K";
} else if (size < 1073741824) {
fileSizeString = df.format((double) size / 1048576) + "M";
} else {
fileSizeString = df.format((double) size / 1073741824) + "G";
}
return fileSizeString;
}