【无标题】

父类
public class FilterOutputStream extends OutputStream {

//new FileOutputStream("hhy.txt")
protected OutputStream out;


//out - new FileOutputStream("hhy.txt")
public FilterOutputStream(OutputStream out) {
    this.out = out;
}

//b - "123abc".getBytes()
public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
}

@SuppressWarnings("try")
public void close() throws IOException {
    try (OutputStream ostream = out) {
        flush();
    }
}

}
子类
public class BufferedOutputStream extends FilterOutputStream {
//缓冲区
protected byte buf[];//new byte[8192];
//缓冲区有效数据量
protected int count;//0

//out - new FileOutputStream("hhy.txt")
public BufferedOutputStream(OutputStream out) {
    this(out, 8192);
}

//out - new FileOutputStream("hhy.txt")
//size - 8192
public BufferedOutputStream(OutputStream out, int size) {
    super(out);
    if (size <= 0) {
        throw new IllegalArgumentException("Buffer size <= 0");
    }
    buf = new byte[size];
}

//b - "123abc".getBytes()
//off - 0
//len - 6
public synchronized void write(byte b[], int off, int len) throws IOException {
    
    //判断将要写入的数据是否大于缓冲区
    if (len >= buf.length) {
     	//将缓冲区的数据写入到文件
        flushBuffer();
        //再将新的数据写入到文件
        out.write(b, off, len);
        return;
    }
    //缓冲区剩余的空间不够本次添加数据的容量
    if (len > buf.length - count) {
        //将缓冲区的数据写入到文件
        flushBuffer();
    }
    //将本次添加的数据写入到数组中
    System.arraycopy(b, off, buf, count, len);
    count += len;
}

private void flushBuffer() throws IOException {
    //判断缓冲区中是否有数据
    if (count > 0) {
        out.write(buf, 0, count);
        count = 0;
    }
}

public synchronized void flush() throws IOException {
    //将缓冲区的数据写入到文件
    flushBuffer();
    out.flush();
}

}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“hhy.txt”));

bos.write(“123abc”.getBytes());
bos.write(“123abc”.getBytes());

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值