Java File Size Get countFileSize(String pathname)

Here you can find the source of countFileSize(String pathname)

Description

count File Size

License

Apache License

Declaration

public static String countFileSize(String pathname) 

Method Source Code

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

import java.io.File;

import java.text.DecimalFormat;

public class Main {

    public static String countFileSize(String pathname) {
        String fileSizeString = "";
        try {/* w w w  . j a va  2  s. c  om*/
            File file = new File(pathname);
            DecimalFormat df = new DecimalFormat("#.00");
            long fileS = file.length();
            if (fileS < 1024) {
                fileSizeString = "0byte";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                fileSizeString = df.format(((double) fileS / 1024 / 1024) - 0.01) + "MB";
            } else {
                fileSizeString = df.format((double) fileS / 1024 / 1024 / 1024) + "G";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSizeString;
    }

    public static String countFileSize(long fileSize) {
        String fileSizeString = "";
        try {
            DecimalFormat df = new DecimalFormat("#.00");
            long fileS = fileSize;
            if (fileS == 0) {
                fileSizeString = "0KB";
            } else if (fileS < 1024) {
                fileSizeString = df.format((double) fileS) + "B";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                fileSizeString = df.format(((double) fileS / 1024 / 1024) - 0.01) + "MB";
            } else {
                fileSizeString = df.format((double) fileS / 1024 / 1024 / 1024) + "G";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileSizeString;
    }
}

Related

  1. countFileDisplaySize(long size)
  2. fileSizeString(long bytes)
  3. getFileKBSize(long fsize)
  4. getFileSize(@Nonnull File file)
  5. getFileSize(File dir)