mirror of
https://gitee.com/dromara/hutool.git
synced 2026-02-09 09:16:26 +08:00
DataSizeUtil改进,兼容GiB等单位名称(issue#ICXXVF@Github)
This commit is contained in:
@@ -44,7 +44,7 @@ public final class DataSize implements Comparable<DataSize> {
|
||||
/**
|
||||
* The pattern for parsing.
|
||||
*/
|
||||
private static final Pattern PATTERN = Pattern.compile("^([+-]?\\d+(\\.\\d+)?)([a-zA-Z]{0,2})$");
|
||||
private static final Pattern PATTERN = Pattern.compile("^([+-]?\\d+(\\.\\d+)?)([a-zA-Z]{0,3})$");
|
||||
|
||||
/**
|
||||
* Bytes per Kilobyte(KB).
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package cn.hutool.v7.core.io.unit;
|
||||
|
||||
import cn.hutool.v7.core.text.CharUtil;
|
||||
import cn.hutool.v7.core.text.StrUtil;
|
||||
|
||||
/**
|
||||
@@ -105,11 +106,16 @@ public enum DataUnit {
|
||||
/**
|
||||
* 通过后缀返回对应的 DataUnit
|
||||
*
|
||||
* @param suffix 单位后缀
|
||||
* @param suffix 单位后缀,如KB、GB、GiB等
|
||||
* @return 匹配到的{@link DataUnit}
|
||||
* @throws IllegalArgumentException 后缀无法识别报错
|
||||
*/
|
||||
public static DataUnit fromSuffix(final String suffix) {
|
||||
public static DataUnit fromSuffix(String suffix) {
|
||||
// issue#ICXXVF 兼容KiB、MiB、GiB
|
||||
if(StrUtil.length(suffix) == 3 && CharUtil.equals(suffix.charAt(1), 'i', true)){
|
||||
suffix = new String(new char[]{suffix.charAt(0), suffix.charAt(2)});
|
||||
}
|
||||
|
||||
for (final DataUnit candidate : values()) {
|
||||
// 支持类似于 3MB,3M,3m等写法
|
||||
if (StrUtil.startWithIgnoreCase(candidate.suffix, suffix)) {
|
||||
|
||||
@@ -83,4 +83,10 @@ public class DataSizeUtilTest {
|
||||
final long bytes = DataSize.parse(size).toBytes();
|
||||
Assertions.assertEquals(10244587, bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void issueICXXVFTest(){
|
||||
final long parse = DataSizeUtil.parse("279.40GiB");
|
||||
Assertions.assertEquals(300003465625L, parse);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user