Java File Size Readable Format formatFileSize(long size)

Here you can find the source of formatFileSize(long size)

Description

Formats file size, applying KB, MB, GB units.

License

Open Source License

Parameter

Parameter Description
size Size to format

Declaration

public static String formatFileSize(long size) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from  www. jav  a2 s.c o m
     * Formats file size, applying KB, MB, GB units.
     * @param size Size to format
     * @return 
     */
    public static String formatFileSize(long size) {
        if (size == 0) {
            return "0";
        }

        if (size < 1024) {
            return size + "B";
        }

        if (size >= 1024 && size < 1048576) {
            return Math.round((size / 1024) * 100.0) / 100.0 + "KB";
        }

        if (size >= 1048576 && size < 1073741824) {
            return Math.round((size / 1024 / 1024) * 100.0) / 100.0 + "MB";
        }

        if (size >= 1073741824 && size < 1099511627776L) {
            return Math.round((size / 1024 / 1024 / 1024) * 100.0) / 100.0 + "GB";
        }

        return Math.round((size / 1024 / 1024 / 1024 / 1024) * 100.0) / 100.0 + "TB";
    }
}

Related

  1. formatFileSize(long bytes, boolean si)
  2. formatFileSize(long fileSize)
  3. formatFileSize(long fileSize)
  4. formatFileSize(long fileSize)
  5. formatFileSize(long fileSizeLong)
  6. formatFileSize(long size)
  7. formatFileSize(long size, String format)
  8. FormatFileSize(String filesize)
  9. formatFilesize(String filesize, int decimalPlaces)