获取外部存储设备状态并计算其容量

获取外部存储设备状态并计算其容量

利用该类,直接调用即可,totalSpace为容量,freeSpace为剩余容量,例 String temp=MyUtil.convertStorage(MyUtil.getSDCardInfo().totalSpace);
package com.lhy.filemanage.myutil;
import java.io.File;
import android.util.Log;
public class MyUtil
{
 /**
  * SD卡数据bean
  * 
  * @author User
  */

 public static class SDCardInfo
 {
  public long totalSpace;
  public long freeSpace;
 }
 /**
  * 获取SD数据
  */

 public static SDCardInfo getSDCardInfo ()
 {
  // 获得外部存储设备的状态,首先判断外部存储设备是否存在
  String sDCardString = android.os.Environment.getExternalStorageState();
  if (sDCardString.equals(android.os.Environment.MEDIA_MOUNTED))
  {
   // 获得SD卡根路径
   File pathFile = android.os.Environment.getExternalStorageDirectory();
   try
   {
    // 获取StatFs对象
    // Android.os下的StatFs类主要用来获取文件系统的状态,能够获取sd卡的大小和剩余空间,获取系统内部空间也就是/system的大小和剩余空间等等。
    // StatFs获取的都是以block【块】为单位的
    android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
    // 获取SDCard上BLOCK总数
    long nTotalBlocks = statfs.getBlockCount();
    // 获取SDCard上每个block的SIZE
    long nBlocSize = statfs.getBlockSize();
    // 获取可供程序使用的Block的数量
    long nAvailaBlock = statfs.getAvailableBlocks();
    // 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
    long nFreeBlock = statfs.getFreeBlocks();
    SDCardInfo info = new SDCardInfo();
    // 计算SDCard 总容量大小MB
    info.totalSpace = nTotalBlocks * nBlocSize;
    // 计算 SDCard 剩余大小MB
    info.freeSpace = nAvailaBlock * nBlocSize;
    return info;
   }
   catch (IllegalArgumentException e)
   {
    Log.e("lhy", e.toString());
   }
  }
  return null;
 }
 // storage, G M K B
 public static String convertStorage ( long size)
 {
  long kb = 1024;
  long mb = kb * 1024;
  long gb = mb * 1024;
  if (size >= gb)
  {
   return String.format("%.1f GB", (float) size / gb);
  }
  else if (size >= mb)
  {
   float f = (float) size / mb;
   return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
  }
  else if (size >= kb)
  {
   float f = (float) size / kb;
   return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
  }
  else
   return String.format("%d B", size);
 }
}
posted on 2013-10-26 16:03  知行立远  阅读(407)  评论(0编辑  收藏  举报