Java Size byteSizeString(long bytes)

Here you can find the source of byteSizeString(long bytes)

Description

Returns a String representing the given bytes, with a textual representation depending if the given amount can be represented as KB, MB, GB or TB

License

Open Source License

Parameter

Parameter Description
bytes The <tt>bytes</tt> to be represented

Exception

Parameter Description
IllegalArgumentException Thrown if <tt>bytes</tt> is negative

Return

The String that represents the given bytes

Declaration

public static String byteSizeString(long bytes) 

Method Source Code

//package com.java2s;
/*/*from  w  ww .j a va 2 s  .  co  m*/
 * This file is part of Musicott software.
 *
 * Musicott software is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Musicott library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Musicott. If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (C) 2015, 2016 Octavio Calleya
 */

import java.math.*;

import java.text.*;

public class Main {
    /**
     * Returns a {@link String} representing the given <tt>bytes</tt>, with a textual representation
     * depending if the given amount can be represented as KB, MB, GB or TB
     *
     * @param bytes The <tt>bytes</tt> to be represented
     *
     * @return The <tt>String</tt> that represents the given bytes
     *
     * @throws IllegalArgumentException Thrown if <tt>bytes</tt> is negative
     */
    public static String byteSizeString(long bytes) {
        if (bytes < 0)
            throw new IllegalArgumentException("Given bytes can't be less than zero");

        String sizeText;
        String[] bytesUnits = { "B", "KB", "MB", "GB", "TB" };
        long bytesAmount = bytes;
        short binRemainder;
        float decRemainder = 0;
        int u;
        for (u = 0; bytesAmount > 1024 && u < bytesUnits.length; u++) {
            bytesAmount /= 1024;
            binRemainder = (short) (bytesAmount % 1024);
            decRemainder += Float.valueOf((float) binRemainder / 1024);
        }
        String remainderStr = String.format("%f", decRemainder).substring(2);
        sizeText = bytesAmount + ("0".equals(remainderStr) ? "" : "," + remainderStr) + " " + bytesUnits[u];
        return sizeText;
    }

    /**
     * Returns a {@link String} representing the given <tt>bytes</tt>, with a textual representation
     * depending if the given amount can be represented as KB, MB, GB or TB, limiting the number
     * of decimals, if there are any
     *
     * @param bytes       The <tt>bytes</tt> to be represented
     * @param numDecimals The maximum number of decimals to be shown after the comma
     *
     * @return The <tt>String</tt> that represents the given bytes
     *
     * @throws IllegalArgumentException Thrown if <tt>bytes</tt> or <tt>numDecimals</tt> are negative
     */
    public static String byteSizeString(long bytes, int numDecimals) {
        if (numDecimals < 0) {
            throw new IllegalArgumentException("Given number of decimals can't be less than zero");
        }

        String byteSizeString = byteSizeString(bytes);
        StringBuilder decimalSharps = new StringBuilder();
        for (int n = 0; n < numDecimals; n++)
            decimalSharps.append("#");
        DecimalFormat decimalFormat = new DecimalFormat("#." + decimalSharps.toString());
        decimalFormat.setRoundingMode(RoundingMode.CEILING);

        int unitPos = byteSizeString.lastIndexOf(' ');
        String stringValue = byteSizeString.substring(0, unitPos);
        stringValue = stringValue.replace(',', '.');
        float floatValue = Float.parseFloat(stringValue);
        byteSizeString = decimalFormat.format(floatValue) + byteSizeString.substring(unitPos);
        return byteSizeString;
    }
}

Related

  1. byteCountToDisplaySize(long bytes)
  2. byteCountToDisplaySize(long size)
  3. byteCountToDisplaySize(long size)
  4. byteCountToDisplaySize(long size)
  5. BytesToHRSize(String len)
  6. bytesToSizeFormat(long bytes)
  7. bytesToString(long sizeInBytes)
  8. bytesToUnits(long size)