1 7 8 package java.io; 9 10 11 26 27 public class ByteArrayOutputStream extends OutputStream { 28 29 32 protected byte buf[]; 33 34 37 protected int count; 38 39 43 public ByteArrayOutputStream() { 44 this(32); 45 } 46 47 54 public ByteArrayOutputStream(int size) { 55 if (size < 0) { 56 throw new IllegalArgumentException ("Negative initial size: " 57 + size); 58 } 59 buf = new byte[size]; 60 } 61 62 67 public synchronized void write(int b) { 68 int newcount = count + 1; 69 if (newcount > buf.length) { 70 byte newbuf[] = new byte[Math.max(buf.length << 1, newcount)]; 71 System.arraycopy(buf, 0, newbuf, 0, count); 72 buf = newbuf; 73 } 74 buf[count] = (byte)b; 75 count = newcount; 76 } 77 78 86 public synchronized void write(byte b[], int off, int len) { 87 if ((off < 0) || (off > b.length) || (len < 0) || 88 ((off + len) > b.length) || ((off + len) < 0)) { 89 throw new IndexOutOfBoundsException (); 90 } else if (len == 0) { 91 return; 92 } 93 int newcount = count + len; 94 if (newcount > buf.length) { 95 byte newbuf[] = new byte[Math.max(buf.length << 1, newcount)]; 96 System.arraycopy(buf, 0, newbuf, 0, count); 97 buf = newbuf; 98 } 99 System.arraycopy(b, off, buf, count, len); 100 count = newcount; 101 } 102 103 111 public synchronized void writeTo(OutputStream out) throws IOException { 112 out.write(buf, 0, count); 113 } 114 115 123 public synchronized void reset() { 124 count = 0; 125 } 126 127 135 public synchronized byte toByteArray()[] { 136 byte newbuf[] = new byte[count]; 137 System.arraycopy(buf, 0, newbuf, 0, count); 138 return newbuf; 139 } 140 141 148 public int size() { 149 return count; 150 } 151 152 159 public String toString() { 160 return new String (buf, 0, count); 161 } 162 163 173 public String toString(String enc) throws UnsupportedEncodingException { 174 return new String (buf, 0, count, enc); 175 } 176 177 199 @Deprecated 200 public String toString(int hibyte) { 201 return new String (buf, hibyte, 0, count); 202 } 203 204 211 public void close() throws IOException { 212 } 213 214 } 215 | Popular Tags |