Java Long Number Readable Format formatBytes(long bytes)

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

Description

Formats bytes in human readable form.

License

Apache License

Parameter

Parameter Description
bytes the number of bytes

Return

the formatted bytes

Declaration

public static String formatBytes(long bytes) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

public class Main {
    /**//  w ww  .  ja v  a2 s .  c om
     * Formats bytes in human readable form.
     * 
     * @param bytes the number of bytes
     * @return the formatted bytes
     */
    public static String formatBytes(long bytes) {
        if (Long.MAX_VALUE == bytes) {
            return "\u221e B ";
        }

        String unit = "B ";
        double value = Math.abs(bytes);

        if (value > 1024) {
            value /= 1024;
            unit = "KB";
        }

        if (value > 1024) {
            value /= 1024;
            unit = "MB";
        }

        if (value > 1024) {
            value /= 1024;
            unit = "GB";
        }

        if (value > 1024) {
            value /= 1024;
            unit = "TB";
        }

        if (value > 1024) {
            value /= 1024;
            unit = "PB";
        }

        if (value > 1024) {
            value /= 1024;
            unit = "EB"; // the Enterprise might still use it. 
        }

        String result = String.format("%,.1f %s", value, unit);

        if (bytes < 0) {
            result = "-" + result;
        }

        return result;
    }
}

Related

  1. convertMbIntoGb(long megaBytes)
  2. formatBytes(long bts)
  3. formatBytes(long bytes)
  4. formatBytes(long bytes)
  5. formatBytes(long bytes)
  6. formatBytes(long bytes)
  7. formatBytes(long bytes)
  8. formatBytes(long bytes)
  9. formatBytes(long bytes)