01: /**
02: * $RCSfile$
03: * $Revision: 42 $
04: * $Date: 2004-10-21 00:28:12 -0700 (Thu, 21 Oct 2004) $
05: *
06: * Copyright (C) 2004 Jive Software. All rights reserved.
07: *
08: * This software is published under the terms of the GNU Public License (GPL),
09: * a copy of which is included in this distribution.
10: */package org.jivesoftware.util;
11:
12: import java.text.DecimalFormat;
13: import java.text.FieldPosition;
14: import java.text.Format;
15: import java.text.ParsePosition;
16:
17: /**
18: * A formatter for formatting byte sizes. For example, formatting 12345 byes results in
19: * "12.1 K" and 1234567 results in "1.18 MB".
20: *
21: * @author Bill Lynch
22: */
23: public class ByteFormat extends Format {
24:
25: /**
26: * Formats a long which represent a number of bytes.
27: */
28: public String format(long bytes) {
29: return format(new Long(bytes));
30: }
31:
32: /**
33: * Formats a long which represent a number of kilobytes.
34: */
35: public String formatKB(long kilobytes) {
36: return format(new Long(kilobytes * 1024));
37: }
38:
39: /**
40: * Format the given object (must be a Long).
41: *
42: * @param obj assumed to be the number of bytes as a Long.
43: * @param buf the StringBuffer to append to.
44: * @param pos
45: * @return A formatted string representing the given bytes in more human-readable form.
46: */
47: public StringBuffer format(Object obj, StringBuffer buf,
48: FieldPosition pos) {
49: if (obj instanceof Long) {
50: long numBytes = ((Long) obj).longValue();
51: if (numBytes < 1024 * 1024) {
52: DecimalFormat formatter = new DecimalFormat("#,##0.0");
53: buf
54: .append(
55: formatter
56: .format((double) numBytes / 1024.0))
57: .append(" K");
58: } else {
59: DecimalFormat formatter = new DecimalFormat("#,##0.0");
60: buf.append(
61: formatter.format((double) numBytes
62: / (1024.0 * 1024.0))).append(" MB");
63: }
64: }
65: return buf;
66: }
67:
68: /**
69: * In this implementation, returns null always.
70: *
71: * @param source
72: * @param pos
73: * @return returns null in this implementation.
74: */
75: public Object parseObject(String source, ParsePosition pos) {
76: return null;
77: }
78: }
|