Java Size getSize(long octets)

Here you can find the source of getSize(long octets)

Description

get Size

License

Open Source License

Declaration

public static String getSize(long octets) 

Method Source Code


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

import java.text.DecimalFormat;

public class Main {
    public static final double KB = Math.pow(2, 10);
    public static final double MB = Math.pow(2, 20);
    public static final double GB = Math.pow(2, 30);
    public static final double TB = Math.pow(2, 40);

    public static String getSize(long octets) {
        String unit;// w  ww.j  a  v a2 s .  c  o m
        double div;
        if (octets < MB) {
            //Return KB
            unit = "KB";
            div = KB;
        } else if (octets < GB) {
            //Return MB
            unit = "MB";
            div = MB;
        } else if (octets < TB) {
            //Return GB
            unit = "GB";
            div = GB;
        } else {
            //Return TB
            unit = "TB";
            div = TB;
        }
        String format = "#.#";
        double size = octets / div;
        String sizeString = (new DecimalFormat(format)).format(size);
        if (size % 1 != 0) {
            while (sizeString.endsWith("0")) {
                format += "#";
                sizeString = (new DecimalFormat(format)).format(size);
            }
        }
        return sizeString + " " + unit;
    }
}

Related

  1. getFormatSize(double size)
  2. getFormatSize(long size)
  3. getFormattedSize(long size)
  4. getReadableByteSize(long size)
  5. getReadableSize(long size)
  6. getSizeAll(final long bytes)
  7. getSizeFormat()
  8. getSizeInKB(String size)
  9. getSizeString(long bytes)