Here you can find the source of toHumanReadableSize(final long pSizeInBytes)
Parameter | Description |
---|---|
pSizeInBytes | the size in byte |
public static String toHumanReadableSize(final long pSizeInBytes)
//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(); } }