沟通非阻塞IO与阻塞IO - 出入流

    技术2022-05-11  10

    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();  }}


    最新回复(0)