SpringBoot 文件大写转换
将文件大小(字节),达到KB的转成KB,达到M的转成M
/**
* 方法一
* @param size
* @return
*/
public static String toSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[]{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,###.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
/**
* 方法二
* @param size
* @return
*/
// 定义单位常量
private static final long KB = 1024L;
private static final long MB = KB * 1024L;
private static final long GB = MB * 1024L;
private static final long TB = GB * 1024L;
public static String readableFileSize(long bytes) {
if (bytes >= TB) {
return String.format("%.2f TB", (double) bytes / TB);
} else if (bytes >= GB) {
return String.format("%.2f GB", (double) bytes / GB);
} else if (bytes >= MB) {
return String.format("%.2f MB", (double) bytes / MB);
} else if (bytes >= KB) {
return String.format("%.2f KB", (double) bytes / KB);
} else {
return String.format("%d B", bytes);
}
}
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/18570115