java根据字节数B转成合适的单位,工具类

Posted 爱米酱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java根据字节数B转成合适的单位,工具类相关的知识,希望对你有一定的参考价值。


public class beautifySizeUtil 
public static String beautifySize(double size)
if (size <= 0) return "0";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];


public static String beautifySize(long size)
if (size <= 0) return "0";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];


//返回该B对应的美化单位
public static String beautifyUnit(long size)
if (size <= 0) return "B";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return units[digitGroups];



//B转KB
public static String beautifyKb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1024);
return beauSize;

//B转MB
public static String beautifyMb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1048576);
return beauSize;

//B转GB
public static String beautifyGb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1073741824);
return beauSize;

//B转TB
public static String beautifyTb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1099511627776L);
return beauSize;


public static void main(String[] args)
System.out.println(beautifySize(1));
System.out.println(beautifySize(2048));
System.out.println(beautifySize(200000));
System.out.println(beautifySize(200000000));
System.out.println(beautifySize(2000000000));

执行结果:

java根据字节数B转成合适的单位,工具类_开发语言

以上是关于java根据字节数B转成合适的单位,工具类的主要内容,如果未能解决你的问题,请参考以下文章

powershell 根据文件中的字节数转换文件大小单位

IO流

Java中对象和JSON互相转换的工具类

在Java中将字节大小转换为人类可读的格式?

计算机中用的各种单位之间是怎么转换的

Java基本类型与包装类