Java Byte Array to String bytesToString(long size)

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

Description

Convert a quantity in bytes to a human-readable string such as "4.0 MB".

License

Apache License

Declaration

public static String bytesToString(long size) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from   w  ww.  j  a  va  2s .  co m
     * Convert a quantity in bytes to a human-readable string such as "4.0 MB".
     */
    public static String bytesToString(long size) {
        long TB = 1L << 40;
        long GB = 1L << 30;
        long MB = 1L << 20;
        long KB = 1L << 10;

        double value;
        String unit;
        if (size >= 2 * TB) {
            value = (double) size / TB;
            unit = "TB";
        } else if (size >= 2 * GB) {
            value = (double) size / GB;
            unit = "GB";
        } else if (size >= 2 * MB) {
            value = (double) size / MB;
            unit = "MB";
        } else if (size >= 2 * KB) {
            value = (double) size / KB;
            unit = "KB";
        } else {
            value = (double) size;
            unit = "B";
        }
        return String.format("%.1f %s", value, unit);
    }
}

Related

  1. bytesToString(int bytes)
  2. bytesToString(int... bytesInt)
  3. bytesToString(long b)
  4. bytesToString(long bytes)
  5. bytesToString(long bytes)
  6. byteTo16String(byte[] bt)
  7. byteToMacString(byte[] data)
  8. byteToStr(byte[] byteArray)
  9. byteToStr(byte[] byteArray)