1. 定义:
此类实现一个字节输出流、其中数据被写入到字节数组中, 缓冲区在数据写入时会自动增长,关闭该流无效,关闭此流后调用方法不会有异常
2. 字段
/**
* The buffer where data is stored.
* 存储数据的缓冲区
*/
protected byte buf[];
/**
* The number of valid bytes in the buffer.
* 缓存区的有效字节数
*/
protected int count;
3. 构造函数:
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
* 创建缓冲区字节数组流,默认大小为32字节
*/
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];
}
4. 具体方法
/**
* Increases the capacity if necessary to ensure that it can hold
* at least the number of elements specified by the minimum
* capacity argument.
* 必要时增加容量以确保它至少可以容纳由minimum capacity参数指定的元素数。
*/
private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buf.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = buf.length;
int newCapacity &#