Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-20 22:13:13
Original
696 people have browsed it

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

Convert Byte Size to Human-Readable Format in Java

Problem:

Converting byte size into a human-readable format, such as "1 Kb" or "1 Mb," is a common requirement. Instead of manually writing this utility in each project, exploring existing libraries for such functionality is desirable.

Solution:

Apache Commons

Apache Commons provides two static methods for converting byte size to a human-readable format:

  • humanReadableByteCountSI(): Uses the International System of Units (SI) convention, where 1000 units of a smaller size equal one unit of a larger size.
  • humanReadableByteCountBin(): Uses the binary convention, where 1024 units of a smaller size equal one unit of a larger size.

Implementation:

public static String humanReadableByteCountSI(long bytes) {
  // ... code from Apache Commons
}

public static String humanReadableByteCountBin(long bytes) {
  // ... code from Apache Commons
}
Copy after login

Example:

System.out.println(humanReadableByteCountSI(1024)); // output: "1.0 kB"
System.out.println(humanReadableByteCountBin(1024)); // output: "1.0 KiB"
Copy after login

The above is the detailed content of How Can I Convert Bytes to 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template