Java File Size Get getSize(long fileSize)

Here you can find the source of getSize(long fileSize)

Description

get Size

License

Apache License

Declaration

public static String getSize(long fileSize) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.DecimalFormat;

public class Main {
    public static final long ONE_KILOBYTE = 1024;
    public static final long ONE_MEGABYTE = ONE_KILOBYTE * ONE_KILOBYTE;
    public static final long ONE_GIGABYTE = ONE_MEGABYTE * ONE_KILOBYTE;
    public static final long ONE_TERABYTE = ONE_GIGABYTE * ONE_KILOBYTE;
    public static final long ONE_PETABYTE = ONE_TERABYTE * ONE_KILOBYTE;

    public static String getSize(long fileSize) {

        String size = getSize(fileSize, 2);

        return size;
    }//from www  . j  av a 2  s . c  o m

    public static String getSize(long fileSize, int precision) {

        if (fileSize < 0) {

            throw new IllegalArgumentException("fileSize must be 0 (zero) or greater");
        }

        if (precision < 0) {

            throw new IllegalArgumentException("precision must be 0 (zero) or greater");
        }

        StringBuilder zeros = new StringBuilder();

        for (int i = 0; i < precision; i++) {

            zeros.append("#");
        }

        DecimalFormat decimalFormat = new DecimalFormat("#." + zeros.toString());
        decimalFormat.setDecimalSeparatorAlwaysShown(false);

        String size;

        if (fileSize / ONE_PETABYTE > 0) {

            size = decimalFormat.format(Double.valueOf(fileSize) / ONE_PETABYTE);

        } else if (fileSize / ONE_TERABYTE > 0) {

            size = decimalFormat.format(Double.valueOf(fileSize) / ONE_TERABYTE);

        } else if (fileSize / ONE_GIGABYTE > 0) {

            size = decimalFormat.format(Double.valueOf(fileSize) / ONE_GIGABYTE);

        } else if (fileSize / ONE_MEGABYTE > 0) {

            size = decimalFormat.format(Double.valueOf(fileSize) / ONE_MEGABYTE);

        } else if (fileSize / ONE_KILOBYTE > 0) {

            size = decimalFormat.format(Double.valueOf(fileSize) / ONE_KILOBYTE);

        } else {

            size = decimalFormat.format(fileSize);
        }

        return size;
    }
}

Related

  1. getFileSizes(File f)
  2. getFileSizeString(File file, boolean si)
  3. getFilesizeString(long size)
  4. getFileSizeStringFor(File file)
  5. getFolderSize(File folder)
  6. getSizeErrorMessage(String pattern, Long maxFileSize, Long fileSize, String fileName)
  7. getStringSizeLengthFile(long size)
  8. humanFileSize(Long longFileSize)
  9. humanReadableFileSize(long size)