如何在Java中将字节大小转换为可读格式? [英] How to convert byte size into human readable format in java?

查看:441
本文介绍了如何在Java中将字节大小转换为可读格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将字节大小转换为可读格式?像1024应该成为1 Kb和1024 * 1024应该成为1Mb。

我有点厌倦了为每个项目写这个实用的方法。在Apache Commons中有没有静态方法?

解决方案

和二进制单元):

  public static String humanReadableByteCount(long bytes,boolean si){
int unit = 1000:1024;
if(bytes int exp =(int)(Math.log(bytes)/ Math.log(unit));
String pre =(si?kMGTPE:KMGTPE)。charAt(exp-1)+(si?:i);
return String.format(%。1f%sB,bytes / Math.pow(unit,exp),pre);



$ b示例输出:



$ b pre> SI BINARY

0:0 B 0 B
27:27 B 27 B
999:999 B 999 B
1000:1.0 kB 1000 B
1023:1.0 kB 1023 B
1024:1.0 kB 1.0 KiB
1728:1.7 kB 1.7 KiB
110592:110.6 kB 108.0 KiB
7077888:7.1 MB 6.8 MiB
452984832:453.0 MB 432.0 MiB
28991029248:29.0 GB 27.0 GiB
1855425871872:1.9 TB 1.7 TiB
9223372036854775807:9.2 EB 8.0 EiB(Long。 MAX_VALUE)






相关文章:


How to convert byte size into human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".

I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?

解决方案

Here is my go at it (no loops and handles both SI units and binary units):

public static String humanReadableByteCount(long bytes, boolean si) {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}

Example output:

                              SI     BINARY

                   0:        0 B        0 B
                  27:       27 B       27 B
                 999:      999 B      999 B
                1000:     1.0 kB     1000 B
                1023:     1.0 kB     1023 B
                1024:     1.0 kB    1.0 KiB
                1728:     1.7 kB    1.7 KiB
              110592:   110.6 kB  108.0 KiB
             7077888:     7.1 MB    6.8 MiB
           452984832:   453.0 MB  432.0 MiB
         28991029248:    29.0 GB   27.0 GiB
       1855425871872:     1.9 TB    1.7 TiB
 9223372036854775807:     9.2 EB    8.0 EiB   (Long.MAX_VALUE)


Related article: Java: Formatting byte size to human readable format

这篇关于如何在Java中将字节大小转换为可读格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆