1 16 package org.apache.cocoon.util; 17 18 import java.io.FilterOutputStream ; 19 import java.io.IOException ; 20 import java.io.OutputStream ; 21 22 31 public final class BufferedOutputStream extends FilterOutputStream { 32 33 protected byte buf[]; 34 35 protected int count; 36 37 44 public BufferedOutputStream(OutputStream out) { 45 this(out, 8192); 46 } 47 48 57 public BufferedOutputStream(OutputStream out, int size) { 58 super(out); 59 if (size <= 0) { 60 throw new IllegalArgumentException ("Buffer size <= 0"); 61 } 62 this.buf = new byte[size]; 63 } 64 65 71 public void write(int b) throws IOException { 72 if (this.count >= this.buf.length) { 73 this.incBuffer(); 74 } 75 this.buf[count++] = (byte)b; 76 } 77 78 94 public void write(byte b[], int off, int len) throws IOException { 95 while (len > buf.length - count) { 96 this.incBuffer(); 97 } 98 System.arraycopy(b, off, buf, count, len); 99 count += len; 100 } 101 102 108 public void flush() throws IOException { 109 } 111 112 118 public void close() throws IOException { 119 realFlush(); 120 super.close (); 121 } 122 123 126 public void realFlush() throws IOException { 127 this.writeBuffer(); 128 this.out.flush(); 129 } 130 131 134 private void writeBuffer() 135 throws IOException { 136 if (this.count > 0) { 137 this.out.write(this.buf, 0, this.count); 138 this.clearBuffer(); 139 } 140 } 141 142 145 private void incBuffer() { 146 byte[] newBuf = new byte[this.buf.length * 2]; 149 System.arraycopy(this.buf, 0, newBuf, 0, this.buf.length); 150 this.buf = newBuf; 151 } 152 153 156 public void clearBuffer() { 157 this.count = 0; 158 } 159 160 163 public int getCount() { 164 return this.count; 165 } 166 } 167 168 | Popular Tags |