Java File Size Readable Format formatSize(long size)

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

Description

Returns a human-readable version of the file size.

License

Open Source License

Parameter

Parameter Description
size the size of a file in units (not in bytes)

Return

a human-readable display value

Declaration

public static String formatSize(long size) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by

public class Main {
    public static final long ONE_K = 1000;
    public static final long ONE_M = ONE_K * ONE_K;
    public static final long ONE_G = ONE_K * ONE_M;

    /**/*from   ww  w . j a  va 2  s . c  o  m*/
     * Returns a human-readable version of the file size.
     *
     * @param size the size of a file in units (not in bytes)
     * @return a human-readable display value
     */
    public static String formatSize(long size) {
        String display;

        if (size / ONE_G > 0) {
            display = String.format("%.2f", (size + 0.0) / ONE_G) + " G";
        } else if (size / ONE_M > 0) {
            display = String.format("%.2f", (size + 0.0) / ONE_M) + " M";
        } else if (size / ONE_K > 0) {
            display = String.format("%.2f", (size + 0.0) / ONE_K) + " K";
        } else {
            display = String.valueOf(size);
        }
        return display;
    }
}

Related

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