Java File Size Readable Format toHumanReadableSize(final long bytes)

Here you can find the source of toHumanReadableSize(final long bytes)

Description

Returns a human readable value in storage units rounded up to two decimal places.

License

Apache License

Parameter

Parameter Description
bytes a parameter

Return

Value in storage units.

Declaration

public static String toHumanReadableSize(final long bytes) 

Method Source Code

//package com.java2s;
/*/*from   ww w.  j  a  va2 s  .  co  m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

public class Main {
    private static final int BASE = 1024;

    /**
     * Returns a human readable value in storage units rounded up to two decimal places.
     * e.g. toHumanReadableSize(1024L * 1024L * 1024l * 10L *) + 1024l * 1024l * 59) returns 1.06 GB
     *
     * @param bytes
     * @return Value in storage units.
     */
    public static String toHumanReadableSize(final long bytes) {
        if (bytes < BASE) {
            return bytes + " B";
        }
        final int baseValue = (63 - Long.numberOfLeadingZeros(bytes)) / 10;
        return String.format("%.2f %sB", (double) bytes / (1L << (baseValue * 10)), " kMGTPE".charAt(baseValue));
    }
}

Related

  1. getReadableFileSize(long size)
  2. getReadableFileSize(long size, boolean abbreviation)
  3. toHuman(Double n)
  4. toHumanReadableByteCount(final long bytes)
  5. toHumanReadableFileSize(long fileSize)