Java Size readableBytes(long byteSize)

Here you can find the source of readableBytes(long byteSize)

Description

Formats byte size in nice format

License

Apache License

Parameter

Parameter Description
byteSize the size in bytes to format

Return

Formatted number of bytes (eg: empty, 15 B, 12kB, 821 kB, 3 MB...)

Declaration

public static String readableBytes(long byteSize) 

Method Source Code

//package com.java2s;
/*//from www .  j a  v  a2s . com
 * Copyright 2004-2010 Information & Software Engineering Group (188/1)
 *                     Institute of Software Technology and Interactive Systems
 *                     Vienna University of Technology, Austria
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.ifs.tuwien.ac.at/dm/somtoolbox/license.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.text.DecimalFormat;
import java.text.NumberFormat;

import java.util.HashMap;

public class Main {
    private static HashMap<String, DecimalFormat> decimalFormats = new HashMap<String, DecimalFormat>();

    /**
     * Formats byte size in nice format
     * 
     * @param byteSize the size in bytes to format
     * @return Formatted number of bytes (eg: empty, 15 B, 12kB, 821 kB, 3 MB...)
     */
    public static String readableBytes(long byteSize) {
        if (byteSize < 0l) {
            return "invalid";
        }
        if (byteSize < 1l) {
            return "empty";
        }

        float byteSizeF = new java.lang.Float(byteSize).floatValue();
        String unit = "bytes";
        float factor = 1f;
        String[] desc = { "B", "kB", "MB", "GB", "TB" };

        java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat();
        decimalFormat.setMaximumFractionDigits(1);
        decimalFormat.setGroupingUsed(true);

        String value = decimalFormat.format(byteSizeF);

        int i = 0;
        while (i + 1 < desc.length
                && (value.length() > 4 || value.length() > 3
                        && value.indexOf('.') < 0)) {
            i++;
            factor = factor * 1024l;
            value = decimalFormat.format(byteSizeF / factor);
        }
        if (value.charAt(0) == '0' && i > 0) { // go one back if a too-big scale is used
            value = decimalFormat.format(java.lang.Math.round(1024
                    * byteSizeF / factor));
            i--;
        }

        if (value.length() > 3 && value.indexOf('.') > 0) {
            value = value.substring(0, value.indexOf('.'));
        }

        unit = desc[i];
        return value + " " + unit;
    }

    /**
     * Formats a double value with the given number of fractionDigits. uses {@link #format(double, int, boolean)} with
     * no trailing zeros.
     */
    public static String format(double number, int fractionDigits) {
        return format(number, fractionDigits, false);
    }

    /**
     * Formats a double value with the given number of fractionDigits.
     * 
     * @param withZeros indicates whether there should be trailing zeros to fill up all fraction digits
     */
    public static String format(double number, int fractionDigits,
            boolean withZeros) {
        return format(number, fractionDigits, withZeros, 1);
    }

    public static String format(double number, int fractionDigits,
            boolean withZeros, int leadingDigits) {
        return getDecimalFormat(fractionDigits, withZeros, leadingDigits)
                .format(number);
    }

    /** Formats a double value with the given number of digits, potentially including leading zeros. */
    public static String format(int number, int digits) {
        return getIntegerFormat(digits).format(number);
    }

    /** Returns a {@link DecimalFormat} with the given number of fractionDigits, with or without trailing zeros. */
    public static DecimalFormat getDecimalFormat(int fractionDigits,
            boolean withZeros, int leadingDigits) {
        String pattern = repeatString(leadingDigits, "0") + "."
                + repeatString(fractionDigits, withZeros ? "0" : "#");
        if (!decimalFormats.containsKey(pattern)) {
            // when initializing number formats, using US locale avoids format troubles on localized OS's (, instead of
            // .)
            DecimalFormat format = (DecimalFormat) NumberFormat
                    .getNumberInstance(java.util.Locale.US);
            format.applyPattern(pattern);
            decimalFormats.put(pattern, format);
        }
        return decimalFormats.get(pattern);
    }

    private static DecimalFormat getDecimalFormat(int digits) {
        String precision = "";
        for (int i = 0; i < digits; i++) {
            precision += "#";
        }
        final DecimalFormat decimalFormat = new DecimalFormat("#."
                + precision);
        return decimalFormat;
    }

    /**
     * Returns a {@link DecimalFormat} intended to formatting integers with the given number of digits, potentially with
     * leading zeros
     */
    public static DecimalFormat getIntegerFormat(int digits) {
        DecimalFormat format = (DecimalFormat) NumberFormat
                .getNumberInstance(java.util.Locale.US);
        format.applyPattern(repeatString(digits, "0"));
        return format;
    }

    public static String repeatString(int num, String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            sb.append(s);
        }
        return sb.toString();
    }
}

Related

  1. getSizeText(long size)
  2. getSpaceSizeFromByte(long xB)
  3. getStringSize(String string)
  4. padString(String stringToPad, int size)
  5. read(byte[] input, int size)
  6. readableSize(long num)
  7. readableSize(long size)
  8. readableSize(long size)
  9. readableSize(long size, DecimalFormat format)