Home > Java > javaTutorial > body text

How Can I Convert Bytes to a Human-Readable Format in Java?

DDD
Release: 2024-11-19 07:12:02
Original
373 people have browsed it

How Can I Convert Bytes to a Human-Readable Format in Java?

How to Convert Byte Size into Human-Readable Format in Java

Converting byte size into a human-readable format is a common task in software development. In Java, there's no built-in method for this, but we can use Apache Commons Lang3 for a handy way to do it.

Apache Commons Lang3 provides two methods for humanizing byte counts:

  • humanReadableByteCountSI: Uses the International System of Units (SI), where 1024 bytes is 1 kilobyte (similar to how 1000 grams is 1 kilogram).
  • humanReadableByteCountBin: Uses a binary system, where 1024 bytes is 1 kibibyte (similar to how 1024 bits is 1 kilobit).

Here's how to use these methods:

import org.apache.commons.lang3.StringUtils;

public class ByteSizeConverter {

    public static void main(String[] args) {
        long bytes = 1024 * 1024;

        // Convert to SI format (e.g., 1 MB)
        String humanReadableBytesSI = StringUtils.humanReadableByteCountSI(bytes);
        System.out.println(humanReadableBytesSI); // "1 MB"

        // Convert to binary format (e.g., 1 MiB)
        String humanReadableBytesBin = StringUtils.humanReadableByteCountBin(bytes);
        System.out.println(humanReadableBytesBin); // "1 MiB"
    }
}
Copy after login

These methods provide a convenient way to represent byte sizes in a human-readable format, regardless of whether you prefer SI or binary units.

The above is the detailed content of How Can I Convert Bytes to a Human-Readable Format 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