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.

JavaCli Tooling

Code

snippet
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

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.