Java File Size Readable Format getReadableFileSize(long size, boolean abbreviation)

Here you can find the source of getReadableFileSize(long size, boolean abbreviation)

Description

Format filesize to human readable format Get size in bytes e.g.

License

Apache License

Declaration

public static String getReadableFileSize(long size, boolean abbreviation) 

Method Source Code

//package com.java2s;
/*#######################################################
 *
 *   Maintained by Gregor Santner, 2017-
 *   https://gsantner.net//*w ww. ja va  2s .  co  m*/
 *
 *   License: Apache 2.0
 *  https://github.com/gsantner/opoc/#licensing
 *  https://www.apache.org/licenses/LICENSE-2.0
 *
#########################################################*/

import java.text.DecimalFormat;

public class Main {
    /**
     * Format filesize to human readable format
     * Get size in bytes e.g. from {@link File} using {@code File#length()}
     */
    public static String getReadableFileSize(long size, boolean abbreviation) {
        if (size <= 0) {
            return "0B";
        }
        String[] units = abbreviation ? new String[] { "B", "kB", "MB", "GB", "TB" }
                : new String[] { "Bytes", "Kilobytes", "Megabytes", "Gigabytes", "Terabytes" };
        int unit = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, unit)) + " " + units[unit];
    }
}

Related

  1. getFileSizeInMB(String fileName)
  2. getHumanSize(File dir)
  3. getReadableFileSize(int size)
  4. getReadableFileSize(long fileSizeInBytes)
  5. getReadableFileSize(long size)
  6. toHuman(Double n)
  7. toHumanReadableByteCount(final long bytes)
  8. toHumanReadableFileSize(long fileSize)
  9. toHumanReadableSize(final long bytes)