Java Size toHumanReadableSize(final long pSizeInBytes)

Here you can find the source of toHumanReadableSize(final long pSizeInBytes)

Description

Formats the given number to a human readable format.

License

Open Source License

Parameter

Parameter Description
pSizeInBytes the size in byte

Return

a human readable string representation

Declaration

public static String toHumanReadableSize(final long pSizeInBytes) 

Method Source Code

//package com.java2s;

import java.text.NumberFormat;

public class Main {
    private static ThreadLocal<NumberFormat> sNumberFormat = new ThreadLocal<NumberFormat>() {
        protected NumberFormat initialValue() {
            NumberFormat format = NumberFormat.getNumberInstance();
            // TODO: Consider making this locale/platform specific, OR a method parameter...
            //            format.setMaximumFractionDigits(2);
            format.setMaximumFractionDigits(0);
            return format;
        }/*  w  w  w.ja v a 2s  . c o m*/
    };

    /**
     * Formats the given number to a human readable format.
     * Kind of like {@code df -h}.
     *
     * @param pSizeInBytes the size in byte
     * @return a human readable string representation
     */
    public static String toHumanReadableSize(final long pSizeInBytes) {
        // TODO: Rewrite to use String.format?
        if (pSizeInBytes < 1024L) {
            return pSizeInBytes + " Bytes";
        } else if (pSizeInBytes < (1024L << 10)) {
            return getSizeFormat().format(pSizeInBytes / (double) (1024L)) + " KB";
        } else if (pSizeInBytes < (1024L << 20)) {
            return getSizeFormat().format(pSizeInBytes / (double) (1024L << 10)) + " MB";
        } else if (pSizeInBytes < (1024L << 30)) {
            return getSizeFormat().format(pSizeInBytes / (double) (1024L << 20)) + " GB";
        } else if (pSizeInBytes < (1024L << 40)) {
            return getSizeFormat().format(pSizeInBytes / (double) (1024L << 30)) + " TB";
        } else {
            return getSizeFormat().format(pSizeInBytes / (double) (1024L << 40)) + " PB";
        }
    }

    private static NumberFormat getSizeFormat() {
        return sNumberFormat.get();
    }
}

Related

  1. size(long l)
  2. size2human(long size)
  3. sizeRenderer(String value)
  4. stringToSize(String sizeString)
  5. toByte(String size)
  6. toReadable(long size)