java 把byte轉化為KB、MB、GB的方法
阿新 • • 發佈:2019-01-06
從伺服器下載一個檔案時候,往往告訴你的是相應的KB,MB,GB。方法如下:
public static String getNetFileSizeDescription(long size) { StringBuffer bytes = new StringBuffer(); DecimalFormat format = new DecimalFormat("###.0"); if (size >= 1024 * 1024 * 1024) { double i = (size / (1024.0 * 1024.0 * 1024.0)); bytes.append(format.format(i)).append("GB"); } else if (size >= 1024 * 1024) { double i = (size / (1024.0 * 1024.0)); bytes.append(format.format(i)).append("MB"); } else if (size >= 1024) { double i = (size / (1024.0)); bytes.append(format.format(i)).append("KB"); } else if (size < 1024) { if (size <= 0) { bytes.append("0B"); } else { bytes.append((int) size).append("B"); } } return bytes.toString(); }
這裡用到了這個類:
DecimalFormat
請參考:Java DecimalFormat 用法