上篇我们写了字节输入流的父类:InputStream,这篇我们接着分析字节输出流的父类:OutputStream。它实现了Closeable, Flushable接口,上篇介绍了Closeable接口,这篇我们就介绍Flushable接口,Flushable接口定义如下:
public interface Flushable {
//通过将任何缓冲的输出写入基础流来刷新此流
void flush() throws IOException;
}
方法:
write(int b)
//将指定的一个字节写入此输出流。int 值为 4 个字节,此方法丢弃 int 类型高位的 3 个字节,只保留低
//位的 1 个字节写入(对字节来说,转为 int 其 3 个高位字节都是全 0 的,所以可以丢弃)。此方法是抽
//象方法,子类必须要进行实现。
public abstract void write(int b) throws IOException;
write(byte b[], int off, int len)
//将 b.length 个字节从指定的 byte 数组写入此输出流。调用 write(b, 0, b.length) 方法。
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
write(byte b[], int off, int len)
//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
public void write(byte b[], int off, int len) throws IOException {
// 如果字节数组为空,抛出异常
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
// 如果下标及范围不合适,抛出范围异常。
throw new IndexOutOfBoundsException();
} else if (len == 0) {
// 如果写入长度为0,不需要处理
return;
}
// 从off下标处开始写入每一个字节到输出流。
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
flush()
//刷新此输出流并强制写出所有缓冲的输出字节。此类未实现具体行为,子类应该复写此方法。
public void flush() throws IOException {
}
close()
//关闭此输出流并释放与此流有关的所有系统资源,此类未实现具体行为,子类应该复写此方法。
public void close() throws IOException {
}