FormatUtil { public static String formatBytes(long bytes) { if (bytes == 1L) { return String.format("%d byte", bytes); } else if (bytes < KIBI) { return String.format("%d bytes", bytes); } else if (bytes < MEBI) { return formatUnits(bytes, KIBI, "KiB"); } else if (bytes < GIBI) { return formatUnits(bytes, MEBI, "MiB"); } else if (bytes < TEBI) { return formatUnits(bytes, GIBI, "GiB"); } else if (bytes < PEBI) { return formatUnits(bytes, TEBI, "TiB"); } else if (bytes < EXBI) { return formatUnits(bytes, PEBI, "PiB"); } else { return formatUnits(bytes, EXBI, "EiB"); } } private  FormatUtil(); static String formatBytes(long bytes); static String formatBytesDecimal(long bytes); static String formatHertz(long hertz); static String formatValue(long value, String unit); static String formatElapsedSecs(long secs); static float round(float d, int decimalPlace); static long getUnsignedInt(int x); static String toUnsignedString(int i); static String toUnsignedString(long l); static String formatError(int errorCode); static final String HEX_ERROR; }
@Test public void testFormatBytes() { assertEquals("0 bytes", FormatUtil.formatBytes(0)); assertEquals("1 byte", FormatUtil.formatBytes(1)); assertEquals("532 bytes", FormatUtil.formatBytes(532)); assertEquals("1 KiB", FormatUtil.formatBytes(1024)); assertEquals("1 GiB", FormatUtil.formatBytes(1024 * 1024 * 1024)); assertEquals("1 TiB", FormatUtil.formatBytes(1099511627776L)); }
@Test public void testFormatBytesWithDecimalSeparator() { String expected1 = "1" + DECIMAL_SEPARATOR + "3 KiB"; String expected2 = "2" + DECIMAL_SEPARATOR + "3 MiB"; String expected3 = "2" + DECIMAL_SEPARATOR + "2 GiB"; String expected4 = "1" + DECIMAL_SEPARATOR + "1 TiB"; String expected5 = "1" + DECIMAL_SEPARATOR + "1 PiB"; String expected6 = "1" + DECIMAL_SEPARATOR + "1 EiB"; assertEquals(expected1, FormatUtil.formatBytes(1340)); assertEquals(expected2, FormatUtil.formatBytes(2400016)); assertEquals(expected3, FormatUtil.formatBytes(2400000000L)); assertEquals(expected4, FormatUtil.formatBytes(1099511627776L + 109951162777L)); assertEquals(expected5, FormatUtil.formatBytes(1125899906842624L + 112589990684262L)); assertEquals(expected6, FormatUtil.formatBytes(1152921504606846976L + 115292150460684698L)); }