Java File Size Readable Format formatSize(Long size)

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

Description

Formats a file size.

License

Open Source License

Parameter

Parameter Description
size the file size in bytes

Return

formatted file size, e.g. 1 KB, 2 MB, etc

Declaration

public static String formatSize(Long size) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from w  w  w. j a v  a  2  s .  com*/
     * Formats a file size.
     * @param size the file size in bytes
     * @return formatted file size, e.g. 1 KB, 2 MB, etc
     */
    public static String formatSize(Long size) {
        if (size == null) {
            return null;
        }

        // Based on code by aioobe, http://stackoverflow.com/a/3758880
        int unit = 1024;
        if (size < unit) {
            return String.format("%d B", size);
        }

        int exp = (int) (Math.log(size) / Math.log(unit));
        return String.format("%.2f %cB", size / Math.pow(unit, exp), "KMGTPE".charAt(exp - 1));
    }
}

Related

  1. formatSize(long size)
  2. formatSize(long size)
  3. formatSize(long size)
  4. formatSize(long size)
  5. formatSize(long size)
  6. formatSize(long size)
  7. FormatSize(long size)
  8. formatSize(long v)
  9. formatSize(String strSize)