KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > io > TCByteArrayOutputStream


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.io;
5
6 import java.io.OutputStream JavaDoc;
7
8 /**
9  * No-synch, reset()'able byte array stream, with public access to underlying
10  * byte[]
11  *
12  * @author teck
13  */

14 public final class TCByteArrayOutputStream extends OutputStream JavaDoc {
15
16     private int size;
17
18     private byte[] buffer;
19
20     public TCByteArrayOutputStream() {
21         this(64);
22     }
23
24     public TCByteArrayOutputStream(int initialSize) {
25         buffer = new byte[initialSize];
26     }
27
28     private void ensureCapacity(int newCap) {
29         byte newBuffer[] = new byte[Math.max(buffer.length * 2, newCap)];
30         System.arraycopy(buffer, 0, newBuffer, 0, size);
31         buffer = newBuffer;
32     }
33
34     public final void write(int b) {
35         int newSize = size + 1;
36         if (newSize > buffer.length)
37             ensureCapacity(newSize);
38         buffer[size] = (byte) b;
39         size = newSize;
40     }
41
42     public final void write(byte b[], int offset, int len) {
43         int newSize = size + len;
44         if (newSize > buffer.length)
45             ensureCapacity(newSize);
46         System.arraycopy(b, offset, buffer, size, len);
47         size = newSize;
48     }
49
50     public final void reset() {
51         size = 0;
52     }
53
54     public final byte[] getInternalArray() {
55         return buffer;
56     }
57
58     public final int size() {
59         return size;
60     }
61
62 }
63
Popular Tags