import java.io.IOException;import java.io.OutputStream;import java.nio.ByteBuffer;import java.nio.channels.WritableByteChannel;
public class ChannelOutputStream extends OutputStream {
private WritableByteChannel channel;
private ByteBuffer buffer;
private int bufferSize;
private int bufferCount;
public ChannelOutputStream(WritableByteChannel channel) throws IllegalArgumentException { this(channel, 1024); }
public ChannelOutputStream(WritableByteChannel channel, int bufferSize) throws IllegalArgumentException { if (channel == null) { throw new IllegalArgumentException("The writable byte channel is null"); }
if (bufferSize < 1) { throw new IllegalArgumentException("The buffer size is less than 1"); }
this.channel = channel; this.buffer = ByteBuffer.allocate(bufferSize); this.bufferSize = bufferSize; this.bufferCount = 0; }
public void write(int b) throws IOException { buffer.put((byte) b); bufferCount++; if (bufferCount >= bufferSize) { flush(); } }
public void flush() throws IOException { buffer.flip(); channel.write(buffer); buffer.clear(); bufferCount = 0; }
public void close() throws IOException { if (bufferCount > 0) { flush(); } channel.close(); }}
