java kb,mb,gb互相转换工具类
时间: 2023-10-11 17:08:25 浏览: 161
c# java互相转换工具
3星 · 编辑精心推荐
以下是一个 Java 工具类,可用于将文件大小从 KB、MB、GB 之间相互转换:
```java
public class FileSizeConverter {
public static final long KB = 1024L;
public static final long MB = KB * 1024L;
public static final long GB = MB * 1024L;
public static String convertFileSize(long size) {
if(size < KB) {
return String.format("%d B", size);
} else if(size < MB) {
return String.format("%.2f KB", (double) size / KB);
} else if(size < GB) {
return String.format("%.2f MB", (double) size / MB);
} else {
return String.format("%.2f GB", (double) size / GB);
}
}
public static long convertKBtoBytes(long kb) {
return kb * KB;
}
public static long convertMBtoBytes(long mb) {
return mb * MB;
}
public static long convertGBtoBytes(long gb) {
return gb * GB;
}
public static long convertBytestoKB(long bytes) {
return bytes / KB;
}
public static long convertBytestoMB(long bytes) {
return bytes / MB;
}
public static long convertBytestoGB(long bytes) {
return bytes / GB;
}
}
```
其中,`convertFileSize` 方法用于将文件大小转换为字符串,例如:
```java
long fileSize = 1024 * 1024 * 50; // 50 MB
String fileSizeStr = FileSizeConverter.convertFileSize(fileSize);
System.out.println(fileSizeStr); // 输出:50.00 MB
```
另外还有一些方法,用于进行单位之间的转换,例如:
```java
long kb = 1024;
long bytes = FileSizeConverter.convertKBtoBytes(kb);
System.out.println(bytes); // 输出:1048576
long mb = 50;
bytes = FileSizeConverter.convertMBtoBytes(mb);
System.out.println(bytes); // 输出:52428800
```
阅读全文