KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > util > ByteFormat


1 /**
2  * $RCSfile: ByteFormat.java,v $
3  * $Revision: 1.2 $
4  * $Date: 2004/10/21 07:28:12 $
5  *
6  * Copyright (C) 2004 Jive Software. All rights reserved.
7  *
8  * This software is published under the terms of the GNU Public License (GPL),
9  * a copy of which is included in this distribution.
10  */

11
12 package org.jivesoftware.util;
13
14 import java.text.DecimalFormat JavaDoc;
15 import java.text.FieldPosition JavaDoc;
16 import java.text.Format JavaDoc;
17 import java.text.ParsePosition JavaDoc;
18
19 /**
20  * A formatter for formatting byte sizes. For example, formatting 12345 byes results in
21  * "12.1 K" and 1234567 results in "1.18 MB".
22  *
23  * @author Bill Lynch
24  */

25 public class ByteFormat extends Format JavaDoc {
26
27     /**
28      * Formats a long which represent a number of bytes.
29      */

30     public String JavaDoc format(long bytes) {
31         return format(new Long JavaDoc(bytes));
32     }
33
34     /**
35      * Formats a long which represent a number of kilobytes.
36      */

37     public String JavaDoc formatKB(long kilobytes) {
38         return format(new Long JavaDoc(kilobytes * 1024));
39     }
40
41     /**
42      * Format the given object (must be a Long).
43      *
44      * @param obj assumed to be the number of bytes as a Long.
45      * @param buf the StringBuffer to append to.
46      * @param pos
47      * @return A formatted string representing the given bytes in more human-readable form.
48      */

49     public StringBuffer JavaDoc format(Object JavaDoc obj, StringBuffer JavaDoc buf, FieldPosition JavaDoc pos) {
50         if (obj instanceof Long JavaDoc) {
51             long numBytes = ((Long JavaDoc)obj).longValue();
52             if (numBytes < 1024 * 1024) {
53                 DecimalFormat JavaDoc formatter = new DecimalFormat JavaDoc("#,##0.0");
54                 buf.append(formatter.format((double)numBytes / 1024.0)).append(" K");
55             }
56             else {
57                 DecimalFormat JavaDoc formatter = new DecimalFormat JavaDoc("#,##0.0");
58                 buf.append(formatter.format((double)numBytes / (1024.0 * 1024.0))).append(" MB");
59             }
60         }
61         return buf;
62     }
63
64     /**
65      * In this implementation, returns null always.
66      *
67      * @param source
68      * @param pos
69      * @return returns null in this implementation.
70      */

71     public Object JavaDoc parseObject(String JavaDoc source, ParsePosition JavaDoc pos) {
72         return null;
73     }
74 }
Popular Tags