实现说明
逻辑集中在类 HumanFileSize和函数 human、main里。
这个文件只在 while (value >= 1024 && unit < UNITS.length - 1) 里循环。守卫条件成立时抛出 IllegalArgumentException,而不是返回一个假值。
使用要点
- 执行文件,
main会按顺序走完human。
常见问题
坏输入有失败路径吗?
在真正开工之前就会抛出 IllegalArgumentException——请在调用点处理,或有意向上传播。
「人类可读的文件大小单位」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
主要签名是 static String human(long bytes)
核心语句
return (unit == 0 ? (long) value : rounded) + " " + UNITS[unit];
throw new IllegalArgumentException("negative size: " + bytes);
代码示例
public class HumanFileSize {
private static final String[] UNITS = {"B", "KiB", "MiB", "GiB", "TiB"};
// 二进制单位阶梯:除以 1024 直到数值小于 1024;B 不带小数,其余保留一位
static String human(long bytes) {
if (bytes < 0) {
throw new IllegalArgumentException("negative size: " + bytes);
}
double value = bytes;
int unit = 0;
while (value >= 1024 && unit < UNITS.length - 1) {
value /= 1024;
unit++;
}
double rounded = Math.round(value * 10) / 10.0;
return (unit == 0 ? (long) value : rounded) + " " + UNITS[unit];
}
public static void main(String[] args) {
for (long size : new long[] {0, 512, 1023, 1024, 1536, 1048576, 1584230400, 9_000_000_000L}) {
System.out.println(size + " -> " + human(size));
}
}
}