Display a reasonable indicator of file size

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";
	}

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.