KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > util > ByteArrayOutputStream


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.activemq.util;
19
20 import java.io.OutputStream JavaDoc;
21
22
23 /**
24  * Very similar to the java.io.ByteArrayOutputStream but this version
25  * is not thread safe and the resulting data is returned in a ByteSequence
26  * to avoid an extra byte[] allocation.
27  */

28 public class ByteArrayOutputStream extends OutputStream JavaDoc {
29
30     byte buffer[];
31     int size;
32
33     public ByteArrayOutputStream() {
34         this(1028);
35     }
36     public ByteArrayOutputStream(int capacity) {
37         buffer = new byte[capacity];
38     }
39
40     public void write(int b) {
41         int newsize = size + 1;
42         checkCapacity(newsize);
43         buffer[size] = (byte) b;
44         size = newsize;
45     }
46
47     public void write(byte b[], int off, int len) {
48         int newsize = size + len;
49         checkCapacity(newsize);
50         System.arraycopy(b, off, buffer, size, len);
51         size = newsize;
52     }
53     
54     /**
55      * Ensures the the buffer has at least the minimumCapacity specified.
56      * @param i
57      */

58     private void checkCapacity(int minimumCapacity) {
59         if (minimumCapacity > buffer.length) {
60             byte b[] = new byte[Math.max(buffer.length << 1, minimumCapacity)];
61             System.arraycopy(buffer, 0, b, 0, size);
62             buffer = b;
63         }
64     }
65
66     public void reset() {
67         size = 0;
68     }
69
70     public ByteSequence toByteSequence() {
71         return new ByteSequence(buffer, 0, size);
72     }
73     
74     public byte[] toByteArray() {
75         byte rc[] = new byte[size];
76         System.arraycopy(buffer, 0, rc, 0, size);
77         return rc;
78     }
79     
80     public int size() {
81         return size;
82     }
83 }
84
Popular Tags