01: package com.tagtraum.perf.gcviewer.util;
02:
03: import java.text.NumberFormat;
04: import java.text.FieldPosition;
05: import java.text.ParsePosition;
06:
07: /**
08: * MemoryFormat.
09: * <p/>
10: * Date: Sep 17, 2005
11: * Time: 5:13:32 PM
12: *
13: * @author <a href="mailto:hs@tagtraum.com">Hendrik Schreiber</a>
14: */
15: public class MemoryFormat extends NumberFormat {
16:
17: private static final long ONE_KB = 1024;
18: private static final long TEN_KB = ONE_KB * 10l;
19: private static final long ONE_MB = 1024l * ONE_KB;
20: private static final long TEN_MB = ONE_MB * 10;
21: private NumberFormat format = NumberFormat.getInstance();
22:
23: public MemoryFormat() {
24: format.setMaximumFractionDigits(3);
25: }
26:
27: public void setMaximumFractionDigits(int newValue) {
28: format.setMaximumFractionDigits(newValue);
29: }
30:
31: public StringBuffer format(double memInK, StringBuffer toAppendTo,
32: FieldPosition pos) {
33: final double bytes = memInK * ONE_KB;
34: if (bytes >= TEN_MB) {
35: format.format(bytes / ONE_MB, toAppendTo, pos);
36: toAppendTo.append('M');
37: } else if (bytes >= TEN_KB) {
38: format.format(bytes / ONE_KB, toAppendTo, pos);
39: toAppendTo.append('K');
40: } else {
41: int maxFrac = format.getMaximumFractionDigits();
42: format.setMaximumFractionDigits(0);
43: format.format(bytes, toAppendTo, pos);
44: format.setMaximumFractionDigits(maxFrac);
45: toAppendTo.append('B');
46: }
47: return toAppendTo;
48: }
49:
50: public StringBuffer format(long memInK, StringBuffer toAppendTo,
51: FieldPosition pos) {
52: final double bytes = memInK * ONE_KB;
53: if (bytes >= TEN_MB) {
54: format.format(bytes / ONE_MB, toAppendTo, pos);
55: toAppendTo.append('M');
56: } else if (bytes >= TEN_KB) {
57: format.format(bytes / ONE_KB, toAppendTo, pos);
58: toAppendTo.append('K');
59: } else {
60: int maxFrac = format.getMaximumFractionDigits();
61: format.setMaximumFractionDigits(0);
62: format.format(bytes, toAppendTo, pos);
63: format.setMaximumFractionDigits(maxFrac);
64: toAppendTo.append('B');
65: }
66: return toAppendTo;
67: }
68:
69: public Number parse(String source, ParsePosition parsePosition) {
70: throw new RuntimeException("Not implemented.");
71: }
72: }
|