如何在 Java 中将字节大小转换为人类可读的格式? [英] How can I convert byte size into a human-readable format in Java?

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

问题描述

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

How can I convert byte size into a human-readable format in Java?

像 1024 应该变成1 Kb";并且 1024*1024 应该变成1 Mb".

Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb".

我有点厌烦为每个项目编写这个实用方法.Apache Commons 中是否有用于此的静态方法?

I am kind of sick of writing this utility method for each project. Is there a static method in Apache Commons for this?

推荐答案

有趣的事实:此处发布的原始代码段是 Stack Overflow 上有史以来复制最多的 Java 代码段,并且存在缺陷.它已修复,但变得凌乱.

Fun fact: The original snippet posted here was the most copied Java snippet of all time on Stack Overflow, and it was flawed. It was fixed, but it got messy.

本文的完整故事:有史以来复制次数最多的 Stack Overflow 片段是有缺陷!

来源:将字节大小格式化为人类可读的格式 |编程指南

public static String humanReadableByteCountSI(long bytes) {
    if (-1000 < bytes && bytes < 1000) {
        return bytes + " B";
    }
    CharacterIterator ci = new StringCharacterIterator("kMGTPE");
    while (bytes <= -999_950 || bytes >= 999_950) {
        bytes /= 1000;
        ci.next();
    }
    return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}

二进制 (1 Ki = 1,024)

public static String humanReadableByteCountBin(long bytes) {
    long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
    if (absB < 1024) {
        return bytes + " B";
    }
    long value = absB;
    CharacterIterator ci = new StringCharacterIterator("KMGTPE");
    for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
        value >>= 10;
        ci.next();
    }
    value *= Long.signum(bytes);
    return String.format("%.1f %ciB", value / 1024.0, ci.current());
}

示例输出:

                              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)

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

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