How to get File Size in Bytes KB MB GB TB

1. Overview

In this example, we will write generic method to get file size in bytes, kilobytes, mega bytes, GB,TB.

2. File Size in B,KB,MB,GB and TB Example

  1. The readableFileSize() method in the example, pass the size of the file in long type.
  2. The readableFileSize() method returns String representing the file size (B,KB,MB,GB,TB).
import java.io.File;
import java.text.DecimalFormat;

/**
 * This Java program demonstrates how to get file size in bytes, kilobytes, mega bytes, GB,TB.
 * @author javaguides.net
 */

public class FileUtils {
 /**
     * Given the size of a file outputs as human readable size using SI prefix.
     * <i>Base 1024</i>
     * @param size Size in bytes of a given File.
     * @return SI String representing the file size (B,KB,MB,GB,TB).
     */
    public static String readableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[] {"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int)(Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) 
          + " " + units[digitGroups];
    }
    
    public static void main(String[] args) {
     File file = new File("sample.txt");
     String size = readableFileSize(file.length());
     System.out.println(size);
    }
}
Output:
64 B
Increase the file and test it again.
164 KB

3. Reference

Comments