Java Size getBytesSpecificationDescription(double sizeInBytes, String formatSpec)

Here you can find the source of getBytesSpecificationDescription(double sizeInBytes, String formatSpec)

Description

Returns a short string description of the size, in bytes, specified.

License

Open Source License

Parameter

Parameter Description
sizeInBytes the number of bytes whose size if to be described.
formatSpec the <code>DecimalFormal</code> format specification.

Return

a short-hand string description of the size in bytes.

Declaration

public static String getBytesSpecificationDescription(double sizeInBytes, String formatSpec) 

Method Source Code


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

import java.text.DecimalFormat;

public class Main {
    public static long KBYTES = 1024;
    public static long MEGA_BYTES = KBYTES * KBYTES;
    public static long GIGA_BYTES = MEGA_BYTES * KBYTES;
    public static long TERA_BYTES = GIGA_BYTES * KBYTES;

    /**/*from w  w w  .j a va2  s  . c o m*/
     * Returns a short string description of the size, in bytes, specified.
     *
     * @param sizeInBytes the number of bytes whose size if to be described.
     * @param formatSpec the <code>DecimalFormal</code> format specification.
     * @return a short-hand string description of the size in bytes.
     * @see java.text.DateFormat
     */
    public static String getBytesSpecificationDescription(double sizeInBytes, String formatSpec) {
        DecimalFormat df = new DecimalFormat(formatSpec);
        df.setDecimalSeparatorAlwaysShown(false);
        double teraBytes = sizeInBytes / TERA_BYTES;
        if (teraBytes >= 1.0d) {
            return df.format(teraBytes) + " TB";
        }

        double gigaBytes = sizeInBytes / GIGA_BYTES;
        if (gigaBytes >= 1.0d) {
            return df.format(gigaBytes) + " GB";
        }

        double megaBytes = sizeInBytes / MEGA_BYTES;
        if (megaBytes >= 1.0d) {
            return df.format(megaBytes) + " MB";
        }

        double kBytes = sizeInBytes / KBYTES;
        if (kBytes >= 1.0d) {
            return df.format(kBytes) + " KB";
        }

        return ((long) sizeInBytes) + " Bytes";
    }

    /**
     * Returns a short string description of the size, in bytes, specified.
     *
     * @param sizeInBytes the number of bytes whose size if to be described.
     * @return a short-hand string description of the size in bytes.
     */
    public static String getBytesSpecificationDescription(double sizeInBytes) {
        return getBytesSpecificationDescription(sizeInBytes, "#.##");
    }
}

Related

  1. bytesToSizeFormat(long bytes)
  2. bytesToString(long sizeInBytes)
  3. bytesToUnits(long size)
  4. calcSize(double s, String type, int div)
  5. createSizeFormat(Locale locale)
  6. getByteStr(long size)
  7. getDataSize(long size)
  8. getFontSizeInPoints(String fontSizeWithUnit)
  9. getFormatSize(double size)