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的任意输出流中 */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值