Java Get file size in units like kb mb gb


Best way to get human-readable version of the file size in Java is using byteCountToDisplaySize method of FileUtils class of Apache Commons IO Java library. Commons IO is well tested library. The Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more.

Methods used
//Returns a human-readable version of the file size
//where the input represents a specific number of bytes.
public static String byteCountToDisplaySize(BigInteger size)

//Returns a human-readable version of the file size
//where the input represents a specific number of bytes.
public static String byteCountToDisplaySize(long size)

Platform information

jdk1.8.0_60, Java 8, Eclipse

Library Information

Used library Name:

Commons IO

Maven Dependency Entry
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Gradle Dependency Entry
compile \'commons-io:commons-io:2.4\'
Jar Download Location

Download Jar

Sample code to get file size in Human readable unit

package org.code4copy;

import java.math.BigInteger;

import org.apache.commons.io.FileUtils;

public class HumanReadableFileSize {
        public static void main(String[] args) {
                System.out.println("Size value of 1024*1024*1024: " + 
                                FileUtils.byteCountToDisplaySize(1024*1024*1024));
                
                BigInteger size = new BigInteger("1234567891234");
                System.out.println("Size vale of Size of 1024*1024*1024*1024: " + 
                                FileUtils.byteCountToDisplaySize(size));
                
                size = new BigInteger("12345678912345678912345");
                System.out.println("Size vale of Size of 1024*1024*1024: " + 
                                FileUtils.byteCountToDisplaySize(size));
        }
}

Output of program

Size value of 1024*1024*1024: 1 GB
Size vale of Size of 1024*1024*1024*1024: 1 TB
Size vale of Size of 1024*1024*1024: 10708 EB

Download code from here


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.