View Javadoc

1   package org.lcsim.util.cache;
2   
3   import java.text.DecimalFormat;
4   import java.text.FieldPosition;
5   import java.text.Format;
6   import java.text.ParsePosition;
7   
8   /**
9    * A formatter for formatting byte sizes. For example, formatting 12345 byes
10   * results in "12.1 kB" and 1234567 results in "1.18 MB".
11   * 
12   * @author Bill Lynch
13   * @author Tony Johnson
14   */
15  public class ByteFormat extends Format {
16  
17      private final static String[] mags = { " B", " kB", " MB", " GB", " TB", " PB" };
18      private final static DecimalFormat formatter = new DecimalFormat("#,##0.0");
19  
20      /**
21       * Formats a long which represent a number of bytes.
22       */
23      public String format(long bytes) {
24          return format(new Long(bytes));
25      }
26  
27      /**
28       * Format the given object (must be a Long).
29       * 
30       * @param obj assumed to be the number of bytes as a Long.
31       * @param buf the StringBuffer to append to.
32       * @param pos
33       * @return A formatted string representing the given bytes in more
34       *         human-readable form.
35       */
36      public StringBuffer format(Object obj, StringBuffer buf, FieldPosition pos) {
37          if (obj instanceof Long) {
38              long numBytes = ((Long) obj).longValue();
39              if (numBytes > 1024) {
40                  int mag = 1;
41                  for (; mag < mags.length; mag++) {
42                      if (numBytes < 1024 * 1024)
43                          break;
44                      numBytes /= 1024;
45                  }
46  
47                  buf.append(formatter.format((double) numBytes / 1024.0)).append(mags[mag]);
48              } else {
49                  buf.append(numBytes).append(mags[0]);
50              }
51          }
52          return buf;
53      }
54  
55      /**
56       * In this implementation, returns null always.
57       * 
58       * @param source
59       * @param pos
60       * @return returns null in this implementation.
61       */
62      public Object parseObject(String source, ParsePosition pos) {
63          return null;
64      }
65  }