home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1998 January / PCO0198.ISO / 1&1 / java.z / java_301 / java / io / ByteArrayOutputStream.class (.txt) < prev    next >
Encoding:
Java Class File  |  1996-10-20  |  1.8 KB  |  65 lines

  1. package java.io;
  2.  
  3. public class ByteArrayOutputStream extends OutputStream {
  4.    protected byte[] buf;
  5.    protected int count;
  6.  
  7.    public ByteArrayOutputStream() {
  8.       this(32);
  9.    }
  10.  
  11.    public ByteArrayOutputStream(int size) {
  12.       this.buf = new byte[size];
  13.    }
  14.  
  15.    public synchronized void write(int b) {
  16.       int newcount = this.count + 1;
  17.       if (newcount > this.buf.length) {
  18.          byte[] newbuf = new byte[Math.max(this.buf.length << 1, newcount)];
  19.          System.arraycopy(this.buf, 0, newbuf, 0, this.count);
  20.          this.buf = newbuf;
  21.       }
  22.  
  23.       this.buf[this.count] = (byte)b;
  24.       this.count = newcount;
  25.    }
  26.  
  27.    public synchronized void write(byte[] b, int off, int len) {
  28.       int newcount = this.count + len;
  29.       if (newcount > this.buf.length) {
  30.          byte[] newbuf = new byte[Math.max(this.buf.length << 1, newcount)];
  31.          System.arraycopy(this.buf, 0, newbuf, 0, this.count);
  32.          this.buf = newbuf;
  33.       }
  34.  
  35.       System.arraycopy(b, off, this.buf, this.count, len);
  36.       this.count = newcount;
  37.    }
  38.  
  39.    public synchronized void writeTo(OutputStream out) throws IOException {
  40.       out.write(this.buf, 0, this.count);
  41.    }
  42.  
  43.    public synchronized void reset() {
  44.       this.count = 0;
  45.    }
  46.  
  47.    public synchronized byte[] toByteArray() {
  48.       byte[] newbuf = new byte[this.count];
  49.       System.arraycopy(this.buf, 0, newbuf, 0, this.count);
  50.       return newbuf;
  51.    }
  52.  
  53.    public int size() {
  54.       return this.count;
  55.    }
  56.  
  57.    public String toString() {
  58.       return new String(this.toByteArray(), 0);
  59.    }
  60.  
  61.    public String toString(int hibyte) {
  62.       return new String(this.toByteArray(), hibyte);
  63.    }
  64. }
  65.