Parsing human-readable filesizes in Java to Bytes

java

Solution

Use `BigDecimal` instead:

BigDecimal bytes = new BigDecimal("1.2GB".replace("GB", ""));
bytes = bytes.multiply(BigDecimal.valueOf(1024).pow(3));
long value = bytes.longValue();

Which you can put in a method:

public static long toBytes(String filesize) {
    long returnValue = -1;
    Pattern patt = Pattern.compile("([\\d.]+)([GMK]B)", Pattern.CASE_INSENSITIVE);
    Matcher matcher = patt.matcher(filesize);
    Map<String, Integer> powerMap = new HashMap<String, Integer>();
    powerMap.put("GB", 3);
    powerMap.put("MB", 2);
    powerMap.put("KB", 1);
    if (matcher.find()) {
      String number = matcher.group(1);
      int pow = powerMap.get(matcher.group(2).toUpperCase());
      BigDecimal bytes = new BigDecimal(number);
      bytes = bytes.multiply(BigDecimal.valueOf(1024).pow(pow));
      returnValue = bytes.longValue();
    }
    return returnValue;
}

And call it like:

long bytes = toBytes("1.2GB");

Problem

I have a bunch of file sizes that I would like to parse. These are currently only in GBs. Here are some samples: - 1.2GB - 2.4GB I think I should store my byte filesizes in a `Long` value but I can't seem to figure it out. Here's how I'm doing it: ``` System.out.println(Float.parseFloat("1.2GB".replace("GB", ""))* 1024L * 1024L * 1024L); ``` This returns a `Float` value which is displayed as `1.28849024E9`. How can I get a `Long` representation of the filesize in bytes. I've gotten a little confused with the numeric datatypes. Thanks.

Original source

Related problems