Java Size byteCountToDisplaySize(long size)

Here you can find the source of byteCountToDisplaySize(long size)

Description

Returns a human-readable version of the file size, where the input represents a specific number of bytes.

License

Open Source License

Parameter

Parameter Description
size the number of bytes.

Return

a human-readable display value (includes units).

Declaration

public static String byteCountToDisplaySize(long size) 

Method Source Code

//package com.java2s;
/**/* ww w.j av  a 2  s  . com*/
 * Xtreme Media Player a cross-platform media player.
 * Copyright (C) 2005-2011 Besmir Beqiri
 * 
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.text.NumberFormat;

public class Main {
    /**
     * Returns a human-readable version of the file size, where the input
     * represents a specific number of bytes.
     *
     * @param size the number of bytes.
     * @return a human-readable display value (includes units).
     */
    public static String byteCountToDisplaySize(long size) {
        double ONE_KiB_D = 1024D;
        double ONE_MiB_D = ONE_KiB_D * ONE_KiB_D;
        double ONE_GiB_D = ONE_KiB_D * ONE_MiB_D;

        StringBuilder sbResult = new StringBuilder();
        NumberFormat sizeFormat = NumberFormat.getNumberInstance();
        sizeFormat.setMinimumFractionDigits(0);
        sizeFormat.setMaximumFractionDigits(2);
        if (size > ONE_GiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_GiB_D)).append(" GiB");
        } else if (size > ONE_MiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_MiB_D)).append(" MiB");
        } else if (size > ONE_KiB_D) {
            sbResult.append(sizeFormat.format(size / ONE_KiB_D)).append(" KiB");
        } else {
            sbResult.append(String.valueOf(size)).append(" bytes");
        }
        return sbResult.toString();
    }
}

Related

  1. byteCountToDisplaySize(long bytes)
  2. byteCountToDisplaySize(long size)
  3. byteCountToDisplaySize(long size)
  4. byteSizeString(long bytes)
  5. BytesToHRSize(String len)