1 9 10 package com.opensymphony.module.sitemesh.util; 11 12 import java.io.ByteArrayOutputStream ; 13 import java.io.IOException ; 14 import java.io.OutputStream ; 15 import java.io.UnsupportedEncodingException ; 16 import java.util.Iterator ; 17 import java.util.LinkedList ; 18 19 28 public class FastByteArrayOutputStream extends ByteArrayOutputStream { 29 private static final int DEFAULT_BLOCK_SIZE = 8192; 30 31 32 private byte[] buffer; 33 34 private LinkedList buffers; 35 36 private int index; 37 private int size; 38 private int blockSize; 39 40 public FastByteArrayOutputStream() { 41 this(DEFAULT_BLOCK_SIZE); 42 } 43 44 public FastByteArrayOutputStream(int aSize) { 45 blockSize = aSize; 46 buffer = new byte[blockSize]; 47 } 48 49 public void writeTo(OutputStream out) throws IOException { 50 if (buffers != null) { 52 Iterator iterator = buffers.iterator(); 53 while (iterator.hasNext()) { 54 byte[] bytes = (byte[]) iterator.next(); 55 out.write(bytes, 0, blockSize); 56 } 57 } 58 59 out.write(buffer, 0, index); 61 } 62 63 64 public int size() { 65 return size + index; 66 } 67 68 public byte[] toByteArray() { 69 byte[] data = new byte[size()]; 70 71 int pos = 0; 73 if (buffers != null) { 74 Iterator iterator = buffers.iterator(); 75 while (iterator.hasNext()) { 76 byte[] bytes = (byte[]) iterator.next(); 77 System.arraycopy(bytes, 0, data, pos, blockSize); 78 pos += blockSize; 79 } 80 } 81 82 System.arraycopy(buffer, 0, data, pos, index); 84 85 return data; 86 } 87 88 public void write(int datum) { 89 if (index == blockSize) { 90 if (buffers == null) 92 buffers = new LinkedList (); 93 94 buffers.addLast(buffer); 95 96 buffer = new byte[blockSize]; 97 size += index; 98 index = 0; 99 } 100 101 buffer[index++] = (byte) datum; 103 } 104 105 public void write(byte[] data, int offset, int length) { 106 if (data == null) { 107 throw new NullPointerException (); 108 } 109 else if ((offset < 0) || (offset + length > data.length) 110 || (length < 0)) { 111 throw new IndexOutOfBoundsException (); 112 } 113 else { 114 if (index + length >= blockSize) { 115 for (int i = 0; i < length; i++) 118 write(data[offset + i]); 119 } 120 else { 121 System.arraycopy(data, offset, buffer, index, length); 123 index += length; 124 } 125 } 126 } 127 128 public synchronized void reset() { 129 buffer = new byte[blockSize]; 130 buffers = null; 131 } 132 133 public String toString(String enc) throws UnsupportedEncodingException { 134 return new String (toByteArray(), enc); 135 } 136 137 public String toString() { 138 return new String (toByteArray()); 139 } 140 141 public void flush() throws IOException { 142 } 144 145 public void close() throws IOException { 146 } 148 } | Popular Tags |