Java专题十一(2):Flushable与flush方法
描述了实现Flushable接口的类(这里主要是IO输出流Writer和OutputStream的子类),写入输出流时需要将缓冲区中数据刷新到文件、网络等媒介中;
其中,IO输出流Writer和OutputStream的子类中除了BufferedOutputStream、BufferedWriter真正实现flush方法的,其它都是直接调用父类空的flush方法
public interface Flushable {
void flush() throws IOException;
}
中间过渡层,相当于CPU与内存之间的Cache层
待写入的数据 => 缓冲区 => IO输出流
java.io.BufferedOutputStream
为例)8192
)8KB的缓冲区:BufferedOutputStream(OutputStream out)
write(int b)
),先判断缓冲区是否满,如果已满(count >= buf.length
),会自动将数据写入IO输出流中(flushBuffer()
),但缓冲区未满时怎么办呢?flush()
方法手动将缓冲区数据写入IO输出流// java.io.BufferedOutputStream
public class BufferedOutputStream extends FilterOutputStream {
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
public synchronized void write(int b) throws IOException {
if (count >= buf.length) {
flushBuffer();
}
buf[count++] = (byte)b;
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}
}
原文:https://www.cnblogs.com/myibu/p/12936549.html