Java数据单位转换
Java 将byte数据量转换为带适合单位的值,Java9以上适用
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Pattern;
/**
* Convert byte values to values with appropriate data units
*/
public class Conversion {
private static final BigDecimal span = new BigDecimal(1024);
public static final String maxLevelBytes = "1329227995784915872903807060280344576";
private static final String[] units = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "DB", "NB", "DB", "CB"};
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
/**
*
* @param bytes Byte data volume of data
* @return Value with appropriate data units
*/
public static String UnitConversion(String bytes) {
if (isNumeric2(bytes)){
return "0B";
}
BigDecimal bigDecimal = new BigDecimal(bytes);
if (bigDecimal.compareTo(BigDecimal.ZERO) <= 0) {
return "0B";
}
BigDecimal level = new BigDecimal(maxLevelBytes);
int i;
for (i = units.length - 1; i >= 0; i--) {
if (bigDecimal.compareTo(level) > 0) {
break;
}
level = level.divide(span, 0, RoundingMode.DOWN);
}
return bigDecimal.divide(level, 2, RoundingMode.DOWN).toString() + units[i];
}
public static boolean isNumeric2(String str) {
return str != null && NUMBER_PATTERN.matcher(str).matches();
}
}