eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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 SI 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 “207MiB”, or converting “2048 bytes” to “2KiB”.

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

  • Binary Prefixes – They are the powers of 1024; for example, 1MiB = 1024 KiB, 1GiB = 1024 MiB, 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.

Our tutorial will focus on both binary prefixes and SI prefixes.

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 KiB unit, so we have “4 KiB”.

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 KiB = BYTE << 10;
private static long MiB = KiB << 10;
private static long GiB = MiB << 10;
private static long TiB = GiB << 10;
private static long PiB = TiB << 10;
private static long EiB = PiB << 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.

For SI Prefixes one unit multiplied by 1000 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 KB = BYTE * 1000;
private static long MB = KB * 1000;
private static long GB = MB * 1000;
private static long TB = GB * 1000;
private static long PB = TB * 1000;
private static long EB = PB * 1000;

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 KiB as the suitable unit, divider=1024 and unitName = “KiB”.

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 toHumanReadableBinaryPrefixes(long size) {
    if (size < 0)
        throw new IllegalArgumentException("Invalid file size: " + size);
    if (size >= EiB) return formatSize(size, EiB, "EiB");
    if (size >= PiB) return formatSize(size, PiB, "PiB");
    if (size >= TiB) return formatSize(size, TiB, "TiB");
    if (size >= GiB) return formatSize(size, GiB, "GiB");
    if (size >= MiB) return formatSize(size, MiB, "MiB");
    if (size >= KiB) return formatSize(size, KiB, "KiB");
    return formatSize(size, BYTE, "Bytes");
}
public static String toHumanReadableSIPrefixes(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_BINARY_PREFIXES = new HashMap<Long, String>() {{
    put(0L, "0 Bytes");
    put(1023L, "1023 Bytes");
    put(1024L, "1 KiB");
    put(12_345L, "12.06 KiB");
    put(10_123_456L, "9.65 MiB");
    put(10_123_456_798L, "9.43 GiB");
    put(1_777_777_777_777_777_777L, "1.54 EiB");
}};
private final static Map<Long, String> DATA_MAP_SI_PREFIXES = new HashMap<Long, String>() {{
    put(0L, "0 Bytes");
    put(999L, "999 Bytes");
    put(1000L, "1 KB");
    put(12_345L, "12.35 KB");
    put(10_123_456L, "10.12 MB");
    put(10_123_456_798L, "10.12 GB");
    put(1_777_777_777_777_777_777L, "1.78 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 SizeUnitBinaryPrefixes {
    Bytes(1L),
    KiB(Bytes.unitBase << 10),
    MiB(KiB.unitBase << 10),
    GiB(MiB.unitBase << 10),
    TiB(GiB.unitBase << 10),
    PiB(TiB.unitBase << 10),
    EiB(PiB.unitBase << 10);

    private final Long unitBase;

    public static List<SizeUnitBinaryPrefixes> unitsInDescending() {
        List<SizeUnitBinaryPrefixes> list = Arrays.asList(values());
        Collections.reverse(list);
        return list;
    }
   //getter and constructor are omitted
}
enum SizeUnitSIPrefixes {
    Bytes(1L),
    KB(Bytes.unitBase * 1000),
    MB(KB.unitBase * 1000),
    GB(MB.unitBase * 1000),
    TB(GB.unitBase * 1000),
    PB(TB.unitBase * 1000),
    EB(PB.unitBase * 1000);

    private final Long unitBase;

    public static List<SizeUnitSIPrefixes> unitsInDescending() {
        List<SizeUnitSIPrefixes> 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      KiB  	53
2      MiB  	43
3      GiB  	33
4      TiB  	23
5      PiB  	13
6      EiB       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) + "iB");
}

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 “iB” 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments