Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

When we get the size of a file in Java, usually, we'll get the value in bytes. However, once a file is large enough, for example, 123456789 bytes, seeing the length expressed in bytes becomes a challenge for us trying to comprehend how big the file is.

In this tutorial, we'll explore how to convert file size in bytes into a human-readable format in Java.

2. Introduction to the Problem

As we've talked about earlier, when the size of a file in bytes is large, it's not easy to understand for humans. Therefore, when we present an amount of data to humans, we often use a proper binary prefix, such as KB, MB, GB, and so on, to make a large number human-readable. For example, “270GB” is much easier to understand than “282341192 Bytes”.

However, when we get a file size through the standard Java API, usually, it's in bytes. So, to have the human-readable format, we need to dynamically convert the value from the byte unit to the corresponding binary prefix, for example, converting “282341192 bytes” to “207GB”, or converting “2048 bytes” to “2KB”.

It's worth mentioning that there are two variants of the unit prefixes:

  • Binary Prefixes – They are the powers of 1024; for example, 1MB = 1024 KB, 1GB = 1024 MB, and so on
  • SI (International System of Units) Prefixes – They are the powers of 1000; for example, 1MB = 1000 KB, 1GB = 1000 MB, and so on.

In most contexts, industry uses binary prefixes. Therefore, our tutorial will focus on binary prefixes as well.

3. Solving the Problem

We may have already realized that the key to solving the problem is finding the suitable unit dynamically.

For example, if the input is less than 1024, say 200, then we need to take the byte unit to have “200 Bytes”. However, when the input is greater than 1024 but less than 1024 * 1024, for instance, 4096, we should use the KB unit, so we have “4 KB”.

But, let's solve the problem step by step. Before we dive into the unit determination logic, let's first define all required units and their boundaries.

3.1. Defining Required Units

As we've known, one unit multiplied by 1024 will transit to the unit at the next level. Therefore, we can create constants indicating all required units with their base values:

private static long BYTE = 1L;
private static long KB = BYTE << 10;
private static long MB = KB << 10;
private static long GB = MB << 10;
private static long TB = GB << 10;
private static long PB = TB << 10;
private static long EB = PB << 10;

As the code above shows, we've used the binary left shift operator (<<) to calculate the base values. Here, x << 10” does the same as “x * 1024” since 1024 is two to the power of 10.

3.1. Defining the Number Format

Assuming that we've determined the right unit and we want to express the file size to two decimal places, we can create a method to output the result:

private static DecimalFormat DEC_FORMAT = new DecimalFormat("#.##");

private static String formatSize(long size, long divider, String unitName) {
    return DEC_FORMAT.format((double) size / divider) + " " + unitName;
}

Next, let's understand quickly what the method does. As we've seen in the code above, first, we defined the number format DEC_FORMAT.

The divider parameter is the base value of the chosen unit, while the String argument unitName is the unit's name. For example, if we've chosen KB as the suitable unit, divider=1024 and unitName = “KB”.

This method centralizes the division calculation and the number format conversion.

Now, it's time to move to the core part of the solution: finding out the right unit.

3.2. Determining the Unit

Let's first have a look at the implementation of the unit determination method:

public static String toHumanReadable(long size) {
    if (size < 0) {
        throw new IllegalArgumentException("Invalid file size: " + size);
    }
    if (size >= EB) return formatSize(size, EB, "EB");
    if (size >= PB) return formatSize(size, PB, "PB");
    if (size >= TB) return formatSize(size, TB, "TB");
    if (size >= GB) return formatSize(size, GB, "GB");
    if (size >= MB) return formatSize(size, MB, "MB");
    if (size >= KB) return formatSize(size, KB, "KB");
    return formatSize(size, BYTE, "Bytes");
}

Now, let's walk through the method and understand how it works.

First, we want to make sure the input is a positive number.

Then, we check the units in the direction from high (EB) to low (Byte). Once we find the input size is greater than or equal to the current unit's base value, the current unit will be the right one.

As soon as we find the right unit, we can call the previously created formatSize method to get the final result as a String.

3.3. Testing the Solution

Now, let's write a unit test method to verify if our solution works as expected. To simplify testing the method, let's initialize a Map<Long, String> holding inputs and the corresponding expected results:

private static Map<Long, String> DATA_MAP = new HashMap<Long, String>() {{
    put(0L, "0 Bytes");
    put(1023L, "1023 Bytes");
    put(1024L, "1 KB");
    put(12_345L, "12.06 KB");
    put(10_123_456L, "9.65 MB");
    put(10_123_456_798L, "9.43 GB");
    put(1_777_777_777_777_777_777L, "1.54 EB");
}};

Next, let's go through the Map DATA_MAP, taking each key value as the input and verifying if we can obtain the expected result:

DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadable(in)));

When we execute the unit test, it passes.

4. Improving the Solution With an Enum and Loop

So far, we've solved the problem. The solution is pretty straightforward. In the toHumanReadable method, we've written multiple if statements to determine the unit.

If we think about the solution carefully, a couple of points might be error-prone:

  • The order of those if statements must be fixed as they are in the method.
  • In each if statement, we've hard-coded the unit constant and the corresponding name as a String object.

Next, let's see how to improve the solution.

4.1. Creating the SizeUnit enum

Actually, we can convert the unit constants into an enum so that we don't have to hard-code the names in the method:

enum SizeUnit {
    Bytes(1L),
    KB(Bytes.unitBase << 10),
    MB(KB.unitBase << 10),
    GB(MB.unitBase << 10),
    TB(GB.unitBase << 10),
    PB(TB.unitBase << 10),
    EB(PB.unitBase << 10);

    private final Long unitBase;

    public static List<SizeUnit> unitsInDescending() {
        List<SizeUnit> list = Arrays.asList(values());
        Collections.reverse(list);
        return list;
    }
   
    //getter and constructor are omitted
}

As the enum SizeUnit above shows, a SizeUnit instance holds both unitBase and name.

Further, since we want to check the units in “descending” order later, we've created a helper method, unitsInDescending, to return all units in the required order.

With this enum, we don't have to code the names manually. 

Next, let's see if we can make some improvement on the set of if statements.

4.2. Using a Loop to Determine the Unit

As our SizeUnit enum can provide all units in a List in descending order, we can replace the set of if statements with a for loop:

public static String toHumanReadableWithEnum(long size) {
    List<SizeUnit> units = SizeUnit.unitsInDescending();
    if (size < 0) {
        throw new IllegalArgumentException("Invalid file size: " + size);
    }
    String result = null;
    for (SizeUnit unit : units) {
        if (size >= unit.getUnitBase()) {
            result = formatSize(size, unit.getUnitBase(), unit.name());
            break;
        }
    }
    return result == null ? formatSize(size, SizeUnit.Bytes.getUnitBase(), SizeUnit.Bytes.name()) : result;
}

As the code above shows, the method follows the same logic as the first solution. In addition, it avoids those unit constants, multiple if statements, and hard-coded unit names.

To make sure it works as expected, let's test our solution:

DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableWithEnum(in)));

The test passes when we execute it.

5. Using the Long.numberOfLeadingZeros Method

We've solved the problem by checking units one by one and taking the first one that satisfies our condition.

Alternatively, we can use the Long.numberOfLeadingZeros method from the Java standard API to determine which unit the given size value falls in.

Next, let's take a closer look at this interesting approach.

5.1. Introduction to the Long.numberOfLeadingZeros Method

The Long.numberOfLeadingZeros method returns the number of zero bits preceding the leftmost one-bit in the binary representation of the given Long value. 

As Java's Long type is a 64-bit integer, Long.numberOfLeadingZeros(0L) = 64. A couple of examples may help us understand the method quickly:

1L  = 00... (63 zeros in total) ..            0001 -> Long.numberOfLeadingZeros(1L) = 63
1024L = 00... (53 zeros in total) .. 0100 0000 0000 -> Long.numberOfLeadingZeros(1024L) = 53

Now, we've understood the Long.numberOfLeadingZeros method. But why can it help us to determine the unit?

Let's figure it out.

5.2. The Idea to Solve the Problem

We've known the factor between the units is 1024, which is two to the power of ten (2^10). Therefore, if we calculate the number of leading zeros of each unit's base value, the difference between two adjacent units is always 10:

Index  Unit	numberOfLeadingZeros(unit.baseValue)
----------------------------------------------------
0      Byte	63
1      KB  	53
2      MB  	43
3      GB  	33
4      TB  	23
5      PB  	13
6      EB        3

Further, we can calculate the number of leading zeros of the input value and see the result falls in which unit's range to find the suitable unit.

Next, let's see an example – how to determine the unit and calculate the unit base value for the size 4096:

if 4096 < 1024 (Byte's base value)  -> Byte 
else:
    numberOfLeadingZeros(4096) = 51
    unitIdx = (numberOfLeadingZeros(1) - 51) / 10 = (63 - 51) / 10 = 1
    unitIdx = 1  -> KB (Found the unit)
    unitBase = 1 << (unitIdx * 10) = 1 << 10 = 1024

Next, let's implement this logic as a method.

5.3. Implementing the Idea

Let's create a method to implement the idea we've discussed just now:

public static String toHumanReadableByNumOfLeadingZeros(long size) {
    if (size < 0) {
        throw new IllegalArgumentException("Invalid file size: " + size);
    }
    if (size < 1024) return size + " Bytes";
    int unitIdx = (63 - Long.numberOfLeadingZeros(size)) / 10;
    return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "B");
}

As we can see, the method above is pretty compact. It doesn't need unit constants or an enum. Instead, we've created a String containing units: ” KMGTPE”. Then, we use the calculated unitIdx to pick the right unit letter and append the “B” to build the complete unit name.

It's worth mentioning that we leave the first character empty on purpose in the String ” KMGTPE”. This is because the unit “Byte” doesn't follow the pattern “*B“, and we handled it separately: if (size < 1024) return size + ” Bytes”; 

Again, let's write a test method to make sure it works as expected:

DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in)));

6. Using Apache Commons IO

So far, we've implemented two different approaches to converting a file size value into a human-readable format.

Actually, some external library has already provided a method to solve the problem: Apache Commons-IO.

Apache Commons-IO's FileUtils allows us to convert byte size to a human-readable format through the byteCountToDisplaySize method.

However, this method rounds the decimal part up automatically.

Finally, let's test the byteCountToDisplaySize method with our input data and see what it prints:

DATA_MAP.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in)));

The test outputs:

0 bytes -> 0 bytes
1024 bytes -> 1 KB
1777777777777777777 bytes -> 1 EB
12345 bytes -> 12 KB
10123456 bytes -> 9 MB
10123456798 bytes -> 9 GB
1023 bytes -> 1023 bytes

7. Conclusion

In this article, we've addressed different ways to convert file size in bytes into a human-readable format.

As always, the code presented in this article is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!