public static String formatBytes(long bytes) {
if (bytes < 1024L * 100) {
return bytes + "";
} else if ((bytes /= 1024L) < 1024L * 100) {
return bytes + "K";
} else if ((bytes /= 1024L) < 1024L * 100) {
return bytes + "M";
} else if ((bytes /= 1024L) < 1024L * 100) {
return bytes + "G";
} else {
return (bytes / 1024L) + "T";
}
}
public static long parseBytes(String string) throws NumberFormatException {
int i = 0;
while (i < string.length()) {
if (!Character.isDigit(string.charAt(i))) {
break;
}
i++;
}
long size = Long.parseLong(string.substring(0, i));
switch (string.substring(i).trim().toLowerCase()) {
case "t": case "tb": size *= 1024L; /* no break */
case "g": case "gb": size *= 1024L; /* no break */
case "m": case "mb": size *= 1024L; /* no break */
case "k": case "kb": size *= 1024L; /* no break */
case "": break;
default: throw new NumberFormatException("Cannot parse into bytes: " + string);
}
return size;
}
formatBytes 、parseBytes,摘自javacpp
最新推荐文章于 2025-04-15 21:28:53 发布
这段代码展示了如何实现将字节数转换为KB、MB、GB、TB的格式,并提供了一个反向解析字符串回原始字节数的方法。函数考虑了数值范围并处理了单位的匹配。
178

被折叠的 条评论
为什么被折叠?



