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
10
11
12
13
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
22
23 public String format(long bytes) {
24 return format(new Long(bytes));
25 }
26
27
28
29
30
31
32
33
34
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
57
58
59
60
61
62 public Object parseObject(String source, ParsePosition pos) {
63 return null;
64 }
65 }