Java Long Number Readable Format getHumanReadableFileSize(Long fileSize)

Here you can find the source of getHumanReadableFileSize(Long fileSize)

Description

get Human Readable File Size

License

Open Source License

Declaration

public static String getHumanReadableFileSize(Long fileSize) 

Method Source Code


//package com.java2s;
import java.text.DecimalFormat;

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

    public static String getHumanReadableFileSize(Long fileSize) {
        if (fileSize == null)
            return null;
        return getHumanReadableFileSize(fileSize.longValue());
    }/*ww w  .  j  ava 2 s.c  o  m*/

    public static String getHumanReadableFileSize(long fileSize) {
        if (fileSize < 0) {
            return String.valueOf(fileSize);
        }
        String result = getHumanReadableFileSize(fileSize, ONE_PB, "PB");
        if (result != null) {
            return result;
        }

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

    private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
        if (fileSize == 0)
            return "0";

        if (fileSize / unit >= 1) {
            double value = fileSize / (double) unit;
            DecimalFormat df = new DecimalFormat("######.##" + unitName);
            return df.format(value);
        }
        return null;
    }
}

Related

  1. formatBytes(long bytes)
  2. formatBytes(long d)
  3. formatBytes(long l)
  4. formatBytes(long size)
  5. getHumanReadable(long ts, boolean addUTC)
  6. getHumanReadableIfSpeed(long ifSpeed)
  7. getHumanReadableSize(long bytes)
  8. getHumanReadableSize(long fileSize)
  9. getHumanReadableSize(long size, long unit, String unitName)