Java - Convert Human Readable Size to Bytes
I've never heard about such well-known library, which implements such text-parsing utility methods. But your solution seems to be near from correct implementation.
The only two things, which I'd like to correct in your code are:
define method
Number parse(String arg0)
as static due to it utility naturedefine
factor
s for each type of size definition asfinal static
fields.
I.e. it will be like this one:
private final static long KB_FACTOR = 1024;
private final static long MB_FACTOR = 1024 * KB_FACTOR;
private final static long GB_FACTOR = 1024 * MB_FACTOR;
public static double parse(String arg0) {
int spaceNdx = arg0.indexOf(" ");
double ret = Double.parseDouble(arg0.substring(0, spaceNdx));
switch (arg0.substring(spaceNdx + 1)) {
case "GB":
return ret * GB_FACTOR;
case "MB":
return ret * MB_FACTOR;
case "KB":
return ret * KB_FACTOR;
}
return -1;
}
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 not1.6GB
) - Does not support spaces (so, you can use
1GB
but not1 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.
A revised version of Andremoniy's answer that properly distinguishes between kilo and kibi, etc.
private final static long KB_FACTOR = 1000;
private final static long KIB_FACTOR = 1024;
private final static long MB_FACTOR = 1000 * KB_FACTOR;
private final static long MIB_FACTOR = 1024 * KIB_FACTOR;
private final static long GB_FACTOR = 1000 * MB_FACTOR;
private final static long GIB_FACTOR = 1024 * MIB_FACTOR;
public static double parse(String arg0) {
int spaceNdx = arg0.indexOf(" ");
double ret = Double.parseDouble(arg0.substring(0, spaceNdx));
switch (arg0.substring(spaceNdx + 1)) {
case "GB":
return ret * GB_FACTOR;
case "GiB":
return ret * GIB_FACTOR;
case "MB":
return ret * MB_FACTOR;
case "MiB":
return ret * MIB_FACTOR;
case "KB":
return ret * KB_FACTOR;
case "KiB":
return ret * KIB_FACTOR;
}
return -1;
}