What is FileUtils.byteCountToDisplaySize in Java?

Overview

byteCountToDisplaySize() is a staticThis describes the methods in Java that can be called without creating an object of the class. method of the FileUtils class that is used to convert the number of bytes to human-readable format.

If the byte size is over 1 GB, then the size is rounded down to the nearest GB.

How to import FileUtils

The definition of FileUtils can be found in the Apache Commons IO package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
</dependency>

For other versions of the commons-io package, refer to the Maven Repository.

You can import the FileUtils class as follows:


import org.apache.commons.io.FileUtils;

Syntax


public static String byteCountToDisplaySize(final BigInteger size)

Parameters

  • final BigInteger size: This is the number of bytes.

Return value

This method returns a human-readable display value that includes the units: EB, PB, TB, GB, MB, KB, or bytes.

Code

import org.apache.commons.io.FileUtils;
public class Main{
public static void main(String[] args){
// Example 1
long fileSize = 1234542L;
System.out.printf("The output of FileUtils.byteCountToDisplaySize(%s) is '%s'", fileSize, FileUtils.byteCountToDisplaySize(fileSize));
System.out.println();
// Example 2
fileSize = 12345423432L;
System.out.printf("The output of FileUtils.byteCountToDisplaySize(%s) is '%s'", fileSize, FileUtils.byteCountToDisplaySize(fileSize));
System.out.println();
}
}

Example 1

  • file size = 1234542

The method returns 1 MB, rounding the value to the nearest MB.

Example 2

  • file size = 12345423432

The method returns 11 GB, rounding the value to the nearest GB.

Output

The output of the code is as follows:


The output of FileUtils.byteCountToDisplaySize(1234542) is '1 MB'
The output of FileUtils.byteCountToDisplaySize(12345423432) is '11 GB'

Free Resources

Attributions:
  1. undefined by undefined