1
22
23 package com.liferay.portal.kernel.io.unsync;
24
25 import java.io.IOException;
26 import java.io.OutputStream;
27 import java.io.UnsupportedEncodingException;
28
29
38 public class UnsyncByteArrayOutputStream extends OutputStream {
39
40 public UnsyncByteArrayOutputStream() {
41 this(32);
42 }
43
44 public UnsyncByteArrayOutputStream(int size) {
45 buffer = new byte[size];
46 }
47
48 public void reset() {
49 index = 0;
50 }
51
52 public int size() {
53 return index;
54 }
55
56 public byte[] toByteArray() {
57 byte[] newBuffer = new byte[index];
58
59 System.arraycopy(buffer, 0, newBuffer, 0, index);
60
61 return newBuffer;
62 }
63
64 public String toString() {
65 return new String(buffer, 0, index);
66 }
67
68 public String toString(String charsetName)
69 throws UnsupportedEncodingException {
70
71 return new String(buffer, 0, index, charsetName);
72 }
73
74 public void write(byte[] byteArray) {
75 write(byteArray, 0, byteArray.length);
76 }
77
78 public void write(byte[] byteArray, int offset, int length) {
79 if (length <= 0) {
80 return;
81 }
82
83 int newIndex = index + length;
84
85 if (newIndex > buffer.length) {
86 int newBufferSize = Math.max(buffer.length << 1, newIndex);
87
88 byte[] newBuffer = new byte[newBufferSize];
89
90 System.arraycopy(buffer, 0, newBuffer, 0, index);
91
92 buffer = newBuffer;
93 }
94
95 System.arraycopy(byteArray, offset, buffer, index, length);
96
97 index = newIndex;
98 }
99
100 public void write(int b) {
101 int newIndex = index + 1;
102
103 if (newIndex > buffer.length) {
104 int newBufferSize = Math.max(buffer.length << 1, newIndex);
105
106 byte[] newBuffer = new byte[newBufferSize];
107
108 System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
109
110 buffer = newBuffer;
111 }
112
113 buffer[index] = (byte)b;
114
115 index = newIndex;
116 }
117
118 public void writeTo(OutputStream outputStream) throws IOException {
119 outputStream.write(buffer, 0, index);
120 }
121
122 protected byte[] buffer;
123 protected int index;
124
125 }