Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.9k points)
How to convert byte size into a 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?

1 Answer

0 votes
by (46k points)

Here's an Apache Common static method:

Syntax:

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)

Refer to this article for more Java: Formatting byte size to human-readable format

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 24, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...