BufferedOutputStream实现了一个缓冲输出流。构建了这样一个输出流后,应用可以往底层流写数据而不用每次写一个字节都调用底层流的方法。
案例 (java代码): public class BufferedOutputStream extends FilterOutputStream {
-
-
- protected byte buf[];
-
-
- protected int count;
-
-
- 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];
- }
-
-
- private void flushBuffer() throws IOException {
- if (count > 0) {
- out.write(buf, 0, count);
- count = 0;
- }
- }
-
-
- public synchronized void write(int b) throws IOException {
-
- if (count >= buf.length) {
- flushBuffer();
- }
- buf[count++] = (byte)b;
- }
-
-
- 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;
- }
-
-
-
- public synchronized void flush() throws IOException {
- flushBuffer();
- out.flush();
- }
- }
|