Givemepass's Android 惡補筆記

如何判斷檔案大小

| Comments

如果知道一個檔案size有多大, 可以利用下列方法進行字樣的呈現。

private final static long BYTE = 1024L;
private final static long K_BYTE = 1048576L;
private final static long M_BYTE = 1073741824L;
private final static long G_BYTE = 1099511627776L;
public static String fileSizeFormat(long size) {
  DecimalFormat sizeFormat = new DecimalFormat("#.##");
  String fileSizeFormat = "";
  
  if (size == 0) {
    return "0 Byte";
  } else if (size < BYTE) {
    fileSizeFormat = sizeFormat.format((double) size) + " Byte";
  } else if (size < K_BYTE) {
        fileSizeFormat = sizeFormat.format((double) size / BYTE) + " KB";
  } else if (size < M_BYTE) {
    fileSizeFormat = sizeFormat.format((double) size / K_BYTE) + " MB";
  } else if (size < G_BYTE) {
    fileSizeFormat = sizeFormat.format((double) size / M_BYTE) + " GB";
  } else {
    fileSizeFormat = sizeFormat.format((double) size / G_BYTE) + " TB";
  }
  return fileSizeFormat;
}

關於DecimalFormat的用法可參考
用NumberFormat來將數字格式化技巧

Comments

comments powered by Disqus