Java File Size Get getFilesize(String path)

Here you can find the source of getFilesize(String path)

Description

Returns the file size in MB, KB or B rounded to two decimal places.

License

Open Source License

Parameter

Parameter Description
path path to the file

Return

the file size

Declaration

public static String getFilesize(String path) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.text.NumberFormat;

public class Main {
    /**// w  w  w.  jav a 2s. com
     * Returns the file size in MB, KB or B rounded to two decimal places.
     * @param path   path to the file
     * @return the file size
     */
    public static String getFilesize(String path) {
        File file = new File(path);
        long fileSize = file.length();
        float kfileSize = fileSize / 1024;
        float mfileSize = kfileSize / 1024;

        String size;
        if (fileSize > 1048576) {
            size = round(mfileSize, 2) + "MB";
        } else if (fileSize > 1024) {
            size = round(kfileSize, 2) + "KB";
        } else {
            size = Float.toString(fileSize) + "B";
        }
        return size;
    }

    /**
     * Rounds the Rval to the number of places in Rpl
     * @param Rval value to round
     * @param Rpl  number of places to round to
     * @return rounds the given value to the decimal places requested.
     */
    public static String round(float Rval, int Rpl) {
        NumberFormat fmt = NumberFormat.getInstance();
        fmt.setMaximumFractionDigits(Rpl);
        return fmt.format(Rval);
    }
}

Related

  1. getFileSize(String fileSize)
  2. getFileSize(String fn)
  3. getFileSize(String loc)
  4. getFileSize(String path)
  5. getFileSize(String path)
  6. getFileSize2(String filename)
  7. getFileSizeAggregate(String[] files)
  8. getFileSizeFormat(double inputvalue)
  9. getFileSizeFormat(String total_size)