Java Size Format formatFileSize(File file)

Here you can find the source of formatFileSize(File file)

Description

format File Size

License

Open Source License

Parameter

Parameter Description
file the file to return the size of.

Return

a human-readable String representing a file's size. For example, this may return "67.3 KB" or "203.4 MB".

Declaration

public static String formatFileSize(File file) 

Method Source Code

//package com.java2s;
/**//from  w  w w.  j  av  a  2 s  .  c o m
 * This software is released as part of the Pumpernickel project.
 * 
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
 * 
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */

import java.io.File;

import java.text.DecimalFormat;

public class Main {
    static DecimalFormat format = new DecimalFormat("0.0");

    /**
     * @param file
     *            the file to return the size of.
     * @return a human-readable String representing a file's size. For example,
     *         this may return "67.3 KB" or "203.4 MB".
     */
    public static String formatFileSize(File file) {
        return formatFileSize(file.length());
    }

    /**
     * @param byteCount
     *            the size of a file in bytes.
     * @return a human-readable String representing a file's size. For example,
     *         this may return "67.3 KB" or "203.4 MB".
     */
    public static String formatFileSize(long byteCount) {
        if (byteCount < 1024) {
            return byteCount + " bytes";
        } else {
            double d = byteCount;
            d = d / 1024.0;
            if (d < 1024.0) {
                return format.format(d) + " KB";
            }
            d = d / 1024;
            if (d < 1024) {
                return format.format(d) + " MB";
            }
            d = d / 1024;
            if (d < 1024) {
                return format.format(d) + " GB";
            }
            d = d / 1024;
            return format.format(d) + " TB";
        }
    }
}

Related

  1. formatDataSize(final double dataSize)
  2. formatDataSize(long bytes)
  3. formatDecimal(double size)
  4. formatDiskSize(final long diskSize)
  5. formatFileSize(double fileSize, int precision, int unit, boolean showUnit)
  6. formatFilesize(final long filesize, final Locale locale)
  7. formatFilesize(int s)
  8. formatFileSize(long fileS)
  9. formatFilesize(long filesize)