Display a reasonable indicator of file size
Submitted by jhallida on Wed, 04/21/2010 - 12:48
By default, a Java indicator of file size will tell you the number of bytes, but of course a number such as 1042354 isn't exactly user-friendly. Here's a small method to return a human-readable string indication of a number of bytes.
/**
* Return a human-readable indication of a size, given a number of bytes.
* @param bytes the number of bytes
* @return a string such as (1.23GB, 1.4MB, etc.)
*/
public static String stringForBytes(long bytes) {
DecimalFormat deci = new DecimalFormat("0.00");
double gigs = (((double)bytes/1024d)/1024d/1024d);
double megs = (((double)bytes/1024d)/1024d);
double kb = ((double)bytes/1024d);
if (gigs > 1) {
return deci.format(gigs) + " GB";
}
if (megs > 1) {
return deci.format(megs) + " MB";
}
if (kb > 1) {
return deci.format(kb) + " KB";
}
return bytes + " bytes";
}
