现在的位置: 首页 > 综合 > 正文

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

2014年01月28日 ⁄ 综合 ⁄ 共 1137字 ⁄ 字号 评论关闭

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

【上篇】
【下篇】

抱歉!评论已关闭.