Java File Size Get countFileDisplaySize(long size)

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

Description

count File Display Size

License

Open Source License

Declaration

public static String countFileDisplaySize(long size) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.NumberFormat;

public class Main {
    /**/*from   w  w w.  j  a  v a 2  s. co  m*/
     * The number of bytes in a kilobyte.
     */
    public static final long ONE_KB = 1024;
    /**
     * The number of bytes in a megabyte.
     */
    public static final long ONE_MB = ONE_KB * ONE_KB;
    /**
     * The number of bytes in a gigabyte.
     */
    public static final long ONE_GB = ONE_KB * ONE_MB;

    public static String countFileDisplaySize(long size) {
        String displaySize;
        if (size / ONE_GB > 0) {
            displaySize = format(Math.floor(size * 100.0 / ONE_GB) / 100) + "G";
        } else if (size / ONE_MB > 0) {
            displaySize = format(Math.floor(size * 100.0 / ONE_MB) / 100) + "M";
        } else if (size / ONE_KB > 0) {
            displaySize = format(Math.floor(size * 100.0 / ONE_KB) / 100) + "K";
        } else {
            displaySize = size + "Bytes";
        }
        return displaySize;
    }

    private static String format(double number) {
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(0);
        format.setGroupingUsed(false);
        return format.format(number);
    }
}

Related

  1. countFileSize(String pathname)
  2. fileSizeString(long bytes)
  3. getFileKBSize(long fsize)
  4. getFileSize(@Nonnull File file)