Java Long Number Readable Format convertBytes(long bytes)

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

Description

Convert bytes in human readable format(means add KB, MB or GB according to the provided input.

License

Open Source License

Parameter

Parameter Description
bytes the bytes

Return

String

Declaration

public static String convertBytes(long bytes) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * ===========================================================
 * Ankush : Big Data Cluster Management Solution
 * ===========================================================
 * /*  w  w w . ja  v  a 2s.co m*/
 * (C) Copyright 2014, by Impetus Technologies
 * 
 * This is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License (LGPL v3) as
 * published by the Free Software Foundation;
 * 
 * This software 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this software; if not, write to the Free Software Foundation, 
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ******************************************************************************/

import java.text.DecimalFormat;

public class Main {
    /**
     * Convert bytes in human readable format(means add KB, MB or GB according
     * to the provided input.
     * 
     * @param bytes
     *            the bytes
     * @return String
     */
    public static String convertBytes(long bytes) {
        String val = "0";
        if (bytes == 0) {
            return val;
        }

        long KILOBYTE = 1024L;
        long MEGABYTE = 1024L * 1024L;
        long GIGABYTE = 1024L * 1024L * 1024L;
        DecimalFormat df = new DecimalFormat("0.00");

        if (bytes / KILOBYTE >= 0) {
            val = df.format(((bytes * 100.00 / KILOBYTE)) / 100.00) + "KB";
        }
        if (bytes / MEGABYTE > 0) {
            val = df.format(((bytes * 100.00 / MEGABYTE)) / 100.00) + "MB";
        }
        if (bytes / GIGABYTE > 0) {
            val = df.format(((bytes * 100.00 / GIGABYTE)) / 100.00) + "GB";
        }
        return val;
    }
}

Related

  1. bytesToHumanString(long bytes)
  2. bytesToString(long bytes)
  3. convertBytes(long size)
  4. convertByteToGMKB(long bytes)
  5. convertByteUnit(Long l)
  6. convertHumanSize(long byteSize)