java IO 篇之 ByteArrayOutputStream

创建缓冲区,将要写入输出流的数据通过缓存的方式一次性写入
写入输出流的方法如下:
 void writeTo(OutputStream out)
 String toString()


    public ByteArrayOutputStream() {
	this(32); /** 创建一个默认长度为32字节数组 */
    }


    public ByteArrayOutputStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Negative initial size: "
                                               + size);
        }
	buf = new byte[size]; /** 创建指定长度的字节数组*/
    }


public synchronized void write(int b) {
	int newcount = count + 1;
	if (newcount > buf.length) {
            buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
	} /** 写入的字节长度超过数组长度,自动扩展数组长度 */
	buf[count] = (byte)b;
	count = newcount;
    }


public synchronized void write(byte b[], int off, int len) {
	if ((off < 0) || (off > b.length) || (len < 0) ||
            ((off + len) > b.length) || ((off + len) < 0)) {
	    throw new IndexOutOfBoundsException();
	} else if (len == 0) {
	    return;
	}
        int newcount = count + len;
        if (newcount > buf.length) {
            buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
/** 根据要写入的多个字节长度,扩展字节数组长度*/
        }
        System.arraycopy(b, off, buf, count, len); /** 读取多个字节,写入字节数组中*/
        count = newcount;
    }


public synchronized void writeTo(OutputStream out) throws IOException {
	out.write(buf, 0, count); /** 将字节数组中的数据,写入类型为OutputStream的任意输出流中 */
    }

你可能感兴趣的:(java IO 篇之 ByteArrayOutputStream)