Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing human-readable filesizes in Java to Bytes [duplicate]

Tags:

java

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.

like image 258
Mridang Agarwalla Avatar asked Nov 30 '22 02:11

Mridang Agarwalla


2 Answers

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");
like image 54
João Silva Avatar answered Dec 04 '22 01:12

João Silva


This function will give you a more general solution. It covers GB, MB and KB and tolerates both comma and dot for the decimal separator. If a plain integer is entered, it passes it through as well.

public static long parseFilesize(String in) {
  in = in.trim();
  in = in.replaceAll(",",".");
  try { return Long.parseLong(in); } catch (NumberFormatException e) {}
  final Matcher m = Pattern.compile("([\\d.,]+)\\s*(\\w)").matcher(in);
  m.find();
  int scale = 1;
  switch (m.group(2).charAt(0)) {
      case 'G' : scale *= 1024;
      case 'M' : scale *= 1024;
      case 'K' : scale *= 1024; break;
      default: throw new IllegalArgumentException();
  }
  return Math.round(Double.parseDouble(m.group(1)) * scale);
}
like image 23
Marko Topolnik Avatar answered Dec 03 '22 23:12

Marko Topolnik