Java - Convert Human Readable Size to Bytes

Dan Forbes picture Dan Forbes · Jun 6, 2013 · Viewed 9.8k times · Source

I've found lots of information about converting raw byte information into a human-readable format, but I need to do the opposite, i.e. convert the String "1.6 GB" into the long value 1717990000. Is there an in-built/well-defined way to do this, or will I pretty much have to roll my own?

[Edit]: Here is my first stab...

static class ByteFormat extends NumberFormat {
    @Override
    public StringBuffer format(double arg0, StringBuffer arg1, FieldPosition arg2) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public StringBuffer format(long arg0, StringBuffer arg1, FieldPosition arg2) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Number parse(String arg0, ParsePosition arg1) {
        return parse (arg0);
    }

    @Override
    public Number parse(String arg0) {
        int spaceNdx = arg0.indexOf(" ");
        double ret = Double.parseDouble(arg0.substring(0, spaceNdx));
        String unit = arg0.substring(spaceNdx + 1);
        int factor = 0;
        if (unit.equals("GB")) {
            factor = 1073741824;
        }
        else if (unit.equals("MB")) {
            factor = 1048576;
        }
        else if (unit.equals("KB")) {
            factor = 1024;
        }

        return ret * factor;
    }
}

Answer

Utku Özdemir picture Utku Özdemir · Nov 15, 2018

Spring Framework, on version 5.1, added a DataSize class which allows parsing human-readable data sizes into bytes, and also formatting them back to their human-readable form. It can be found here.

If you use Spring Framework, you can upgrade to >=5.1 and use this class. Otherwise you can c/p it and the related classes (while complying to the license).

Then you can use it:

DataSize dataSize = DataSize.parse("16GB");
System.out.println(dataSize.toBytes());

will give the output:

17179869184

However, the pattern used to parse your input

  • Does not support decimals (so, you can use 1GB, 2GB, 1638MB, but not 1.6GB)
  • Does not support spaces (so, you can use 1GB but not 1 GB)

I would recommend to stick to the convention for compatibility/easy maintainability. But if that does not suit your needs, you need to copy & edit the file - it is a good place to start.