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