KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jofti > util > FastByteArrayOutputStream


1 package com.jofti.util;
2
3
4
5 import java.io.OutputStream JavaDoc;
6
7 import java.io.IOException JavaDoc;
8
9 import java.io.InputStream JavaDoc;
10
11 import java.io.ByteArrayInputStream JavaDoc;
12
13
14
15 /**
16
17  * ByteArrayOutputStream implementation that doesn't synchronize methods
18
19  * and doesn't copy the data on toByteArray().
20
21  */

22
23 public class FastByteArrayOutputStream extends OutputStream JavaDoc {
24
25     /**
26
27      * Buffer and size
28
29      */

30
31     protected byte[] buf = null;
32
33     protected int size = 0;
34
35     public int realSize = 0;
36
37     protected int initSize =0;
38
39
40
41     /**
42
43      * Constructs a stream with the given initial size
44
45      */

46
47     public FastByteArrayOutputStream(int initSize) {
48
49         this.size = 0;
50         this.initSize =initSize;
51         this.buf = new byte[initSize];
52
53     }
54
55
56
57     /**
58
59      * Ensures that we have a large enough buffer for the given size.
60
61      */

62
63     private void verifyBufferSize(int sz) {
64
65         if (sz > buf.length) {
66
67             byte[] old = buf;
68
69            
70             buf = new byte[Math.max(sz, buf.length +( buf.length /2))];
71            
72
73             System.arraycopy(old, 0, buf, 0, old.length);
74
75             old = null;
76
77         }
78        
79
80     }
81
82
83
84     public int getSize() {
85
86         return size;
87
88     }
89
90
91
92     /**
93
94      * Returns the byte array containing the written data. Note that this
95
96      * array will almost always be larger than the amount of data actually
97
98      * written.
99
100      */

101
102     public byte[] getByteArray() {
103
104         return buf;
105
106     }
107
108
109
110     public final void write(byte b[]) {
111
112         verifyBufferSize(size + b.length);
113
114         System.arraycopy(b, 0, buf, size, b.length);
115
116         size += b.length;
117
118         realSize+=b.length;
119
120     }
121
122
123
124     public final void write(byte b[], int off, int len) {
125
126         verifyBufferSize(size + len);
127
128         System.arraycopy(b, off, buf, size, len);
129
130         size += len;
131
132         realSize+=len;
133
134     }
135
136
137
138     public final void write(int b) {
139
140         verifyBufferSize(size + 1);
141
142         buf[size++] = (byte) b;
143
144         realSize++;
145
146     }
147
148
149
150     public void reset() {
151         
152  // if (buf.length >initSize){
153
// buf = new byte[initSize];
154
// }
155
//
156
//keep the headers here
157
size = 4;
158         realSize=4;
159
160     }
161
162
163
164   
165
166
167
168 }
169
170
171
172
Popular Tags