Java Size Format formatSize(long sizeInByte)

Here you can find the source of formatSize(long sizeInByte)

Description

Utility method to format a given size in Byte to a human readable format.

License

Open Source License

Parameter

Parameter Description
sizeInByte a parameter

Declaration

public static String formatSize(long sizeInByte) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w  .  j av  a 2 s. c  o  m*/
 * Copyright (C) 2014 TekNux.org
 *
 * This file is part of the dropbitz Community GPL Source Code.
 *
 * dropbitz Community Source Code 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.
 *
 * dropbitz Community Source Code 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 dropbitz Community Source Code.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.text.DecimalFormat;

public class Main {
    private static final int ONE_KILOBYTE_IN_BYTE = 1024;
    private static final String[] FILE_SIZE_UNITS = new String[] { "B", "KiB", "MiB", "GiB", "TiB" };
    private static final DecimalFormat FILE_SIZE_FORMAT = new DecimalFormat("#,##0.#");

    /**
     * Utility method to format a given size in Byte to a human readable format.
     * 1 : "1 B"
     * 1024 : "1 KiB"
     * 2537253 : "2.3 MiB"
     *
     * @param sizeInByte
     * @return
     */
    public static String formatSize(long sizeInByte) {
        if (sizeInByte <= 0) {
            return "0";
        }

        final int digitGroups = (int) (Math.log10(sizeInByte) / Math.log10(ONE_KILOBYTE_IN_BYTE));
        return FILE_SIZE_FORMAT.format(sizeInByte / Math.pow(ONE_KILOBYTE_IN_BYTE, digitGroups)) + " "
                + FILE_SIZE_UNITS[digitGroups];
    }
}

Related

  1. formatSize(long size)
  2. formatSize(long size)
  3. formatSize(long size)
  4. formatSize(long size)
  5. formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)
  6. formatSize(long sizeInBytes)
  7. formatSizeInfo(long size)
  8. formatStorageSize(Double size, String label)