Human Readable File Size Units
Format byte counts through a binary-unit ladder from B to TiB with one-decimal rounding, so reports show 1.5 GiB instead of raw long values.
Code
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));
}
}
}How the snippet works
Human Readable File Size Units comes down to the class HumanFileSize and the functions human and main.
Iteration happens inside while (value >= 1024 && unit < UNITS.length - 1) — everything outside it runs once. A guard precedes the IllegalArgumentException: bad state stops the flow there instead of continuing.
Applying it
Signature: static String human(long bytes)
Start the program and main runs human one after another.
Statements that matter
return (unit == 0 ? (long) value : rounded) + " " + UNITS[unit];
throw new IllegalArgumentException("negative size: " + bytes);
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- Is there a failure path for bad input?
- It throws `IllegalArgumentException` before any real work runs — handle it at the call site or let it propagate deliberately.
- How do you run Human Readable File Size Units?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.