add IOSize.parse(String)

This commit is contained in:
Timi
2025-10-24 11:58:46 +08:00
parent cd9eee61f3
commit 77979be5fe

View File

@ -1,5 +1,10 @@
package com.imyeyu.io; package com.imyeyu.io;
import com.imyeyu.java.TimiJava;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* 字节大小工具 * 字节大小工具
* *
@ -38,20 +43,13 @@ public class IOSize {
EB; EB;
/** /**
* 转换指定单位字节量 * 转换字节量
* *
* @param unit 单位
* @param value 值 * @param value 值
* @return 该单位值字节量 * @return 该单位值字节量
*/ */
public static long value(Unit unit, double value) { public long toBytes(double value) {
Unit[] values = values(); return (long) (value * Math.pow(1024, ordinal()));
for (int i = 0; i < values.length; i++) {
if (values[i] == unit) {
return (long) (value * Math.pow(1024, i));
}
}
return (long) value;
} }
} }
@ -165,4 +163,66 @@ public class IOSize {
} }
return "0"; return "0";
} }
/**
* 将格式化的储存量字符串解析为字节量
* <p>支持格式10GB, 10 GB, 1TB, 1.24 KB 等(单位不区分大小写)</p>
* <pre>
* // 返回 102400
* IOSize.parse("100 KB");
* // 返回 1073741824
* IOSize.parse("1GB");
* </pre>
*
* @param sizeStr 格式化后的储存量字符串
* @return 字节量
* @throws IllegalArgumentException 格式无效
*/
public static long parse(String sizeStr) {
if (TimiJava.isEmpty(sizeStr)) {
throw new IllegalArgumentException("not found sizeStr");
}
// 正则匹配:可选符号 + 数字(含小数点)+ 可选空格 + 单位
Pattern pattern = Pattern.compile("([-+]?\\d+(?:\\.\\d+)?)\\s*([a-zA-Z]+)");
Matcher matcher = pattern.matcher(sizeStr.trim());
if (matcher.find()) {
double value;
try {
value = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid number format: " + matcher.group(1), e);
}
if (value < 0) {
throw new IllegalArgumentException("size cannot be negative: " + value);
}
String unitStr = matcher.group(2).toUpperCase();
Unit unit;
try {
unit = Unit.valueOf(unitStr);
} catch (IllegalArgumentException e) {
// 处理单字母单位缩写K/M/G/T/P/E
unit = switch (unitStr.charAt(0)) {
case 'K' -> Unit.KB;
case 'M' -> Unit.MB;
case 'G' -> Unit.GB;
case 'T' -> Unit.TB;
case 'P' -> Unit.PB;
case 'E' -> Unit.EB;
case 'B' -> Unit.B;
default -> throw new IllegalArgumentException("Unknown unit: " + unitStr);
};
}
return unit.toBytes(value);
}
// 尝试解析纯数字(无单位,默认字节)
try {
long bytes = Long.parseLong(sizeStr.trim());
if (bytes < 0) {
throw new IllegalArgumentException("size cannot be negative: " + bytes);
}
return bytes;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid size format: " + sizeStr, e);
}
}
} }