Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format file size as MB, GB, etc [duplicate]

People also ask

How can I get MB file size?

format("The size of the file: %d bytes", fileSize); These methods will output the size in Bytes. So to get the MB size, you need to divide the file size from (1024*1024).

How do I check the KB of a file?

Step 2: Multiply total number of pixels by the bit depth of the detector (16 bit, 14 bit etc.) to get the total number of bits of data. Step 3: Dividing the total number of bits by 8 equals the file size in bytes. Step 4: Divide the number of bytes by 1024 to get the file size in kilobytes.


public static String readableFileSize(long size) {
    if(size <= 0) return "0";
    final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

This will work up to 1000 TB.... and the program is short!


You'll probably have more luck with java.text.DecimalFormat. This code should probably do it (just winging it though...)

new DecimalFormat("#,##0.#").format(value) + " " + unit


It is surprising for me, but a loop-based algorithm is about 10% faster.

public static String toNumInUnits(long bytes) {
    int u = 0;
    for ( ; bytes > 1024*1024; bytes >>= 10) {
        u++;
    }
    if (bytes > 1024)
        u++;
    return String.format("%.1f %cB", bytes/1024f, " kMGTPE".charAt(u));
}