Java Byte Array to String bytesToString(int bytes)

Here you can find the source of bytesToString(int bytes)

Description

Takes a given int representing a size in bytes and converts it to a String representing the size.

License

Open Source License

Declaration

public static String bytesToString(int bytes) 

Method Source Code

//package com.java2s;
/*/*from www  .j av a2  s  .  co m*/
 *   Copyright 2009 The Portico Project
 *
 *   This file is part of pgauge (a sub-project of Portico).
 *
 *   pgauge is free software; you can redistribute it and/or modify
 *   it under the terms of the Common Developer and Distribution License (CDDL) 
 *   as published by Sun Microsystems. For more information see the LICENSE file.
 *   
 *   Use of this software is strictly AT YOUR OWN RISK!!!
 *   If something bad happens you do not have permission to come crying to me.
 *   (that goes for your lawyer as well)
 *
 */

public class Main {
    /**
     * Takes a given int representing a size in bytes and converts it to a String representing the
     * size. For example, 1024 would yield "1KB". Prints up to two decimal places. Uses "b" for
     * bytes, "KB" for kilobytes and "MB" for megabytes.
     */
    public static String bytesToString(int bytes) {
        int kilobyte = 1024;
        int megabyte = kilobyte * kilobyte;
        String result = null;
        if (bytes >= megabyte)
            result = String.format("%.2f", reduce(bytes, megabyte));
        else if (bytes >= kilobyte)
            result = String.format("%.2f", reduce(bytes, kilobyte));
        else
            result = "" + bytes;

        // String.format() and all that rounds up (which I don't want) and in 1.5 we can't
        // specify the rounding mode on Decimal format, so I'm left to this hack.
        if (result.endsWith("00"))
            result = result.replace(".00", "");
        else if (result.endsWith("0"))
            result = result.substring(0, result.length() - 1);

        if (bytes >= megabyte)
            return result + "MB";
        else if (bytes >= kilobyte)
            return result + "KB";
        else
            return result + "b";
    }

    private static double reduce(int bytes, int unitSize) {
        int main = bytes / unitSize;
        double remainder = ((bytes % unitSize) / (double) unitSize);
        remainder = (double) ((int) (remainder * 100)) / 100;
        return ((double) main) + remainder;
    }
}

Related

  1. bytesToString(byte[] value)
  2. bytesToString(char[] bytes, boolean le, boolean signed)
  3. bytesToString(final byte[] arr, final boolean signed, final boolean littleEndian, final String sep)
  4. bytesToString(final byte[] bytes)
  5. bytesToString(final byte[] data)
  6. bytesToString(int bytes)
  7. bytesToString(int... bytesInt)
  8. bytesToString(long b)
  9. bytesToString(long bytes)