-2

I have a Java variable from datatype long, containing the size of a file in bytes. I want to display the size of the file in a human-readable way:

  1. When the size is at least 1GB, show the size in GB, else step 2
  2. When the size is at least 1MB, show the size in MB, else step 3
  3. When the size is at least 1KB, show the size in KB

It's possible to program this, but I was wondering if there is already a Java framework present which provides this functionality?

For example I have a variable:

long bytes = 1024L;

I want to print this out as String: "1 KB".

Sulejmani
  • 11
  • 2
  • 12
  • Besides that: asking for 3rd party libraries is explicitly off topic here! – GhostCat Aug 02 '18 at 17:35
  • This is not a duplicate. The question explicitly states: ”It's possible to program this, but I was wondering if there is already a Java framework present which provides this functionality?” – VGR Aug 02 '18 at 17:44

2 Answers2

2

You may want to check out Apache Commons FileUtils.byteCountToDisplaySize(long). It handles all possible (non-negative) values of a long.

Usage:

import org.apache.commons.io.FileUtils;

long fileSizeBytes = ...;
FileUtils.byteCountToDisplaySize(fileSizeBytes);
Jeff Brower
  • 594
  • 3
  • 13
1

The closest Java SE has to offer is ChoiceFormat. The easiest way to use a ChoiceFormat is by using MessageFormat’s string representation of it:

long fileSize = /* ... */ ;

String humanReadableSize = MessageFormat.format("{0,choice" +
    ",0#{0,number,integer} B" +
    "|1024#{1,number,0.0} KB" +
    "|" + (1024 * 1024) + "#{2,number,0.0} MB" +
    "|" + (1024 * 1024 * 1024) + "#{3,number,0.0} GB" +
    "}",
    fileSize,
    fileSize / 1024f,
    fileSize / (1024f * 1024f),
    fileSize / (1024f * 1024f * 1024f));
VGR
  • 40,506
  • 4
  • 48
  • 63