Java Size Format formatFileSize(long fileSize, int decimalPos)

Here you can find the source of formatFileSize(long fileSize, int decimalPos)

Description

Formats a file size in hmnan readable form.

License

Open Source License

Parameter

Parameter Description
fileSize the size of the file
decimalPos the number iof decimal places

Return

a formatted file size.

Declaration

public static String formatFileSize(long fileSize, int decimalPos) 

Method Source Code

//package com.java2s;

import java.text.NumberFormat;

public class Main {
    /**/*from  www  .  ja  v  a2s .  com*/
     * 
     */
    private static final int BYTES_IN_KILOBYTE = 1024;

    /**
     * Formats a file size in hmnan readable form.
     * @param fileSize the size of the file
     * @param decimalPos the number iof decimal places
     * @return a formatted file size.
     */
    public static String formatFileSize(long fileSize, int decimalPos) {
        NumberFormat fmt = NumberFormat.getNumberInstance();
        if (decimalPos >= 0) {
            fmt.setMaximumFractionDigits(decimalPos);
        }

        String formattedSize;
        final double size = fileSize;
        double val = size / (BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE);
        if (val > 1) {
            formattedSize = fmt.format(val).concat(" GB");
        } else {
            val = size / (BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE);
            if (val > 1) {
                formattedSize = fmt.format(val).concat(" MB");
            } else {
                val = size / BYTES_IN_KILOBYTE;
                if (val > 1) {
                    formattedSize = fmt.format(val).concat(" KB");
                } else {
                    formattedSize = fmt.format(size).concat(" bytes");
                }
            }
        }

        return formattedSize;
    }
}

Related

  1. formatFileSize(File file)
  2. formatFilesize(final long filesize, final Locale locale)
  3. formatFilesize(int s)
  4. formatFileSize(long fileS)
  5. formatFilesize(long filesize)
  6. formatFileSize(long length)
  7. formatFileSize(long size)
  8. formatFileSize(long size)
  9. formatFileSize(long size)