1 package it.unimi.dsi.fastutil.io; 2 3 23 24 import java.io.IOException ; 25 import java.io.OutputStream ; 26 27 44 45 public class FastBufferedOutputStream extends OutputStream { 46 47 48 public final static int DEFAULT_BUFFER_SIZE = 8 * 1024; 49 50 51 protected byte buffer[]; 52 53 54 protected int pos; 55 56 59 protected int avail; 60 61 62 protected OutputStream os; 63 64 69 70 public FastBufferedOutputStream( final OutputStream os, final int bufSize ) { 71 this.os = os; 72 buffer = new byte[ bufSize ]; 73 avail = bufSize; 74 } 75 76 80 public FastBufferedOutputStream( final OutputStream os ) { 81 this( os, DEFAULT_BUFFER_SIZE ); 82 } 83 84 private void dumpBufferIfFull() throws IOException { 85 if ( avail == 0 ) { 86 os.write( buffer, 0, pos ); 87 pos = 0; 88 avail = buffer.length; 89 } 90 } 91 92 public void write( final int b ) throws IOException { 93 avail--; 94 buffer[ pos++ ] = (byte)b; 95 dumpBufferIfFull(); 96 } 97 98 99 public void write( final byte b[], int offset, int length ) throws IOException { 100 if ( length <= avail ) { 101 System.arraycopy( b, offset, buffer, pos, length ); 102 pos += length; 103 avail -= length; 104 dumpBufferIfFull(); 105 return; 106 } 107 108 System.arraycopy( b, offset, buffer, pos, avail ); 109 os.write( buffer, 0, pos + avail ); 110 111 offset += avail; 112 length -= avail; 113 114 final int residual = length % buffer.length; 115 116 os.write( b, offset, length - residual ); 117 System.arraycopy( b, offset + length - residual, buffer, 0, residual ); 118 pos = residual; 119 avail = buffer.length - residual; 120 } 121 122 public void flush() throws IOException { 123 if ( pos != 0 ) os.write( buffer, 0, pos ); 124 pos = 0; 126 os.flush(); 127 } 128 129 public void close() throws IOException { 130 if ( os == null ) return; 131 if ( pos != 0 ) os.write( buffer, 0, pos ); 132 if ( os != System.out ) os.close(); 133 os = null; 134 buffer = null; 135 } 136 137 } 138 | Popular Tags |