标签:style class blog code java http
成员变量 buf是存储数据的缓冲区 count是缓冲区中的有效字节数。
/**
* The buffer where data is stored.
*/
protected byte buf[];
/**
* The number of valid bytes in the buffer.
*/
protected int count;
构造参数 默认值32,也可以指定缓冲区到大小
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
*/
public ByteArrayOutputStream() {
this(32);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size.
* @exception IllegalArgumentException if size is negative.
*/
public ByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: "
+ size);
}
buf = new byte[size];
}
检查容量是否够用,不够则进行扩容grow。
private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buf.length > 0)
grow(minCapacity);
}
根据所需要到缓冲区大小重新设置缓冲区。
private void grow(int minCapacity) {
//记录旧到缓冲区大小
int oldCapacity = buf.length;
//这里是移位运算 相当于 int newCapacity = oldCapacity X 2;
int newCapacity = oldCapacity << 1;
//如果2倍的大小仍然不够,直接将minCapacity设置为缓冲区大小
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity < 0) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
//重新设置缓冲区
buf = Arrays.copyOf(buf, newCapacity);
}
写入内存流,逻辑就是先判断一下缓冲区是否够用,不够用就先扩容然后再保存。
public synchronized void write(int b) {
ensureCapacity(count + 1);
buf[count] = (byte) b;
count += 1;
}
public synchronized void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) - b.length > 0)) {
throw new IndexOutOfBoundsException();
}
ensureCapacity(count + len);
System.arraycopy(b, off, buf, count, len);
count += len;
}
将缓冲区内容写到输出流当中
public synchronized void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
返回缓冲区内容
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
java.io.ByteArrayOutputStream 源码分析,布布扣,bubuko.com
java.io.ByteArrayOutputStream 源码分析
标签:style class blog code java http
原文地址:http://www.cnblogs.com/daxin/p/3772826.html