父类
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());