java kb mb Gb转换工具类
时间: 2023-10-17 11:23:21 浏览: 48
好的,以下是Java中用于KB/MB/GB转换的工具类代码示例:
```
public class ConvertUtils {
private static final long KB = 1024;
private static final long MB = KB * 1024;
private static final long GB = MB * 1024;
public static String byteToReadable(long bytes) {
if (bytes >= GB) {
return String.format("%.2f GB", (float) bytes / GB);
} else if (bytes >= MB) {
return String.format("%.2f MB", (float) bytes / MB);
} else if (bytes >= KB) {
return String.format("%.2f KB", (float) bytes / KB);
} else {
return String.format("%d Bytes", bytes);
}
}
public static long toByte(String size) {
if (size == null || "".equals(size.trim())) {
return 0;
}
size = size.toUpperCase(Locale.ENGLISH);
String unit = "B";
if (size.endsWith("KB")) {
unit = "KB";
size = size.substring(0, size.length() - 2).trim();
} else if (size.endsWith("MB")) {
unit = "MB";
size = size.substring(0, size.length() - 2).trim();
} else if (size.endsWith("GB")) {
unit = "GB";
size = size.substring(0, size.length() - 2).trim();
} else if (size.endsWith("B")) {
size = size.substring(0, size.length() - 1).trim();
}
double value = Double.parseDouble(size);
if ("KB".equals(unit)) {
value *= KB;
} else if ("MB".equals(unit)) {
value *= MB;
} else if ("GB".equals(unit)) {
value *= GB;
}
return (long) value;
}
}
```
使用方法:
```java
long sizeInBytes = ConvertUtils.toByte("1GB");
String readableSize = ConvertUtils.byteToReadable(sizeInBytes);
System.out.println(readableSize); //expected output: 1.00 GB
```
希望这个工具类能够帮到您。