FileLengthFormat extends Format { @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (!(obj instanceof Long)) { throw new IllegalArgumentException("object must be Long"); } long length = ((Number) obj).longValue(); if (length < KB) { toAppendTo.append(messageSource.getMessage( "sizeX.bytes", new Object[] { formatNumber(length) }, locale)); } else if (length < MB) { toAppendTo.append(messageSource.getMessage( "sizeX.kb", new Object[] { formatNumber(length / (double) KB) }, locale)); } else if (length < GB) { toAppendTo.append(messageSource.getMessage( "sizeX.mb", new Object[] { formatNumber(length / (double) MB) }, locale)); } else { toAppendTo.append(messageSource.getMessage( "sizeX.gb", new Object[] { formatNumber(length / (double) GB) }, locale)); } return toAppendTo; } FileLengthFormat(MessageSource messageSource, Locale locale); @Override StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); String format(long length); @Override Object parseObject(String source, ParsePosition pos);  }
@Test public void format() { when(messageSource.getMessage("sizeX.bytes", new Object[] { "123" }, Locale.US)) .thenReturn("123 bytes"); when(messageSource.getMessage("sizeX.kb", new Object[] { "1.21" }, Locale.US)) .thenReturn("1.21 KB"); when(messageSource.getMessage("sizeX.mb", new Object[] { "1.21" }, Locale.US)) .thenReturn("1.21 MB"); when(messageSource.getMessage("sizeX.gb", new Object[] { "1.21" }, Locale.US)) .thenReturn("1.21 GB"); FileLengthFormat format = new FileLengthFormat(messageSource, Locale.US); assertEquals("123 bytes", format.format(123)); assertEquals("1.21 KB", format.format(1234)); assertEquals("1.21 MB", format.format(1268777)); assertEquals("1.21 GB", format.format(1299227648)); }