Java - 将人类可读大小转换为字节 [英] Java - Convert Human Readable Size to Bytes
问题描述
我发现了很多关于将原始字节信息转换为人类可读格式的信息,但我需要做相反的事情,即将字符串1.6 GB转换为长值1717990000.是否有内置/明确定义的方法,或者我几乎要自己动手?
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?
:这是我的第一次刺...
: 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;
}
}
推荐答案
我从来没有听说过这样一个着名的库,它实现了这种文本解析实用程序方法。但是你的解决方案似乎接近正确的实现。
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:
-
定义方法
数字解析(String arg0)
由于其实用性而为静态
define method
Number parse(String arg0)
as static due to it utility nature
为每种类型的大小定义定义 factor
s为 final static
fields。
define factor
s for each type of size definition as final static
fields.
即它将是这样的:
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;
}
这篇关于Java - 将人类可读大小转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!