UnitConverter { public static long toBytes(String size) { Matcher matcher = NUMBER_AND_UNIT.matcher(size); if (matcher.matches()) { long number = Long.parseLong(matcher.group(1)); String unitStr = matcher.group(2); if (unitStr != null) { char unit = unitStr.toLowerCase().charAt(0); switch (unit) { case 'b': return number; case 'k': return number * K; case 'm': return number * M; case 'g': return number * G; case 't': return number * T; default: throw new IllegalArgumentException("unknown size unit :" + unit); } } else { return number; } } else { throw new IllegalArgumentException("malformed size string: " + size); } }  static long toDurationMillis(String duration); static long toBytes(String size); static String toSizeUnit(Long bytes, int scale); static String toTimeUnit(long millis, int scale); static String toTimeWithMinorUnit(long millis);  }
@Test public void convertSizeBytes() { assertThat(UnitConverter.toBytes("12345")).isEqualTo(12345); assertThat(UnitConverter.toBytes("12b")).isEqualTo(12); assertThat(UnitConverter.toBytes("12k")).isEqualTo(12 * 1024); assertThat(UnitConverter.toBytes("12M")).isEqualTo(12 * 1024 * 1024); assertThat(UnitConverter.toBytes("12G")).isEqualTo(12l * 1024 * 1024 * 1024); assertThat(UnitConverter.toBytes("12T")).isEqualTo(12l * 1024 * 1024 * 1024 * 1024); try { UnitConverter.toBytes("12x"); fail("should fail"); } catch (Throwable t) { assertThat(t).isInstanceOf(IllegalArgumentException.class); } try { UnitConverter.toBytes("a12"); fail("should fail"); } catch (Throwable t) { assertThat(t).isInstanceOf(IllegalArgumentException.class); } }