byteCountToDisplaySize()
is a 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.
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;
public static String byteCountToDisplaySize(final BigInteger size)
final BigInteger size
: This is the number of bytes.This method returns a human-readable display value that includes the units: EB, PB, TB, GB, MB, KB, or bytes.
import org.apache.commons.io.FileUtils;public class Main{public static void main(String[] args){// Example 1long fileSize = 1234542L;System.out.printf("The output of FileUtils.byteCountToDisplaySize(%s) is '%s'", fileSize, FileUtils.byteCountToDisplaySize(fileSize));System.out.println();// Example 2fileSize = 12345423432L;System.out.printf("The output of FileUtils.byteCountToDisplaySize(%s) is '%s'", fileSize, FileUtils.byteCountToDisplaySize(fileSize));System.out.println();}}
file size = 1234542
The method returns 1 MB
, rounding the value to the nearest MB.
file size = 12345423432
The method returns 11 GB
, rounding the value to the nearest GB.
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