Java - 将人类可读大小转换为字节
2022-09-04 05:37:03
我发现了很多关于将原始字节信息转换为人类可读格式的信息,但我需要做相反的事情,即将字符串“1.6 GB”转换为长值1717990000。有没有一个内置的/定义明确的方法来做到这一点,或者我几乎必须自己滚动?
[编辑]:这是我的第一刀...
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;
}
}