Home > Java > javaTutorial > How to Convert Byte Sizes to Human-Readable Formats in Java?

How to Convert Byte Sizes to Human-Readable Formats in Java?

DDD
Release: 2024-11-26 08:08:13
Original
934 people have browsed it

How to Convert Byte Sizes to Human-Readable Formats in Java?

Getting Byte Size in Human-Readable Format in Java

Converting byte sizes into human-readable formats, such as "1 kB" or "1 MB," is a common task in Java programming. While you may often write your own utility methods for this, there are also reusable solutions available.

Apache Commons Static Methods

The Apache Commons Lang library provides static methods for converting byte sizes:

  1. humanReadableByteCountSI: Uses SI units (base 1000) like "GB", "MB", "kB".
  2. humanReadableByteCountBin: Uses binary units (base 1024) like "GiB", "MiB", "KiB".

Implementation Details

Here are the implementations of these methods:

SI Units:

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());
}
Copy after login

Binary Units:

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());
}
Copy after login

Example Output

The following table shows the output for various byte sizes using both SI and Binary methods:

Byte Size SI Binary
0 0 B 0 B
27 27 B 27 B
1024 1.0 kB 1.0 KiB
1728 1.7 kB 1.7 KiB
1855425871872 1.9 TB 1.7 TiB

The above is the detailed content of How to Convert Byte Sizes to Human-Readable Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template