Java File Size Readable Format formatSize(long size)

Here you can find the source of formatSize(long size)

Description

Takes a size of a file or heap of memory in the form of a long and returns a formatted readable version in the form of byte units.

License

Open Source License

Parameter

Parameter Description
size The size in bytes to be formatted.

Return

A formatted string representing the byte size.

Declaration

public static String formatSize(long size) 

Method Source Code

//package com.java2s;

public class Main {
    /**//  w  w  w.  jav  a 2  s  . co  m
     * Takes a size of a file or heap of memory in the form of a long and returns a formatted readable version in the
     * form of byte units. For example, 46 would become 46B, 1,024 would become 1KB, 1,048,576 would become 1MB, etc.
     *
     * @param size The size in bytes to be formatted.
     * @return A formatted string representing the byte size.
     */
    public static String formatSize(long size) {
        if (size < 1024) {
            return size + " B";
        }
        int exp = (int) (Math.log(size) / Math.log(1024));
        return String.format("%.1f %sB", size / Math.pow(1024, exp), "KMGTPE".charAt(exp - 1));
    }
}

Related

  1. formatSize(long bytes)
  2. formatSize(long bytes, String b, String kb, String mb, String gb)
  3. formatSize(long size)
  4. formatSize(long size)
  5. formatSize(long size)
  6. formatSize(long size)
  7. formatSize(long size)
  8. formatSize(long size)
  9. formatSize(long size)