Java Long Number Readable Format getHumanReadableSize(long size, long unit, String unitName)

Here you can find the source of getHumanReadableSize(long size, long unit, String unitName)

Description

get Human Readable Size

License

Open Source License

Declaration

private static String getHumanReadableSize(long size, long unit, String unitName) 

Method Source Code


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

import java.text.DecimalFormat;

public class Main {
    private static long ONE_KB = 1024;
    private static long ONE_MB = ONE_KB * 1024;
    private static long ONE_GB = ONE_MB * 1024;
    private static long ONE_TB = ONE_GB * 1024;
    private static long ONE_PB = ONE_TB * 1024;

    private static String getHumanReadableSize(long size, long unit, String unitName) {
        if (size == 0) {
            return "0";
        }/*from w  w  w.  j  a  v  a2  s.c o  m*/
        if (size / unit >= 1) {
            double value = size / (double) unit;
            DecimalFormat df = new DecimalFormat("######.##" + unitName);
            return df.format(value);
        }
        return null;
    }

    private static String getHumanReadableSize(long size) {
        if (size < 0) {
            return String.valueOf(size);
        }
        String result = getHumanReadableSize(size, ONE_PB, "PB");
        if (result != null) {
            return result;
        }

        result = getHumanReadableSize(size, ONE_TB, "TB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableSize(size, ONE_GB, "GB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableSize(size, ONE_MB, "MB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableSize(size, ONE_KB, "KB");
        if (result != null) {
            return result;
        }
        return String.valueOf(size) + "B";
    }

    public static String getHumanReadableSize(Long Size) {
        if (Size == null) {
            return null;
        }
        return getHumanReadableSize(Size.longValue());
    }
}

Related

  1. getHumanReadable(long ts, boolean addUTC)
  2. getHumanReadableFileSize(Long fileSize)
  3. getHumanReadableIfSpeed(long ifSpeed)
  4. getHumanReadableSize(long bytes)
  5. getHumanReadableSize(long fileSize)
  6. getHumanSize(long size)
  7. getMaxHeap(String message)
  8. getTrafficString(long bytes)
  9. humanize(long value)