提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将字节转换为人类可读的字节计数。
/**NowJava.com - 时 代 Java**/ //package com.nowjava; public class Main { public static void main(String[] argv) throws Exception { long bytes = 2; boolean si = true; System.out.println(humanReadableByteCount(bytes, si)); } /** * Transforms bytes into human readable byte count eg. 110592: 110.6 kB (si = true) 108.0 KiB (si =false) * @param bytes * @param si * @return bytes in readable count and unit */ public static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ?