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

来源:互联网 发布:淘宝网店转让qc41 编辑:程序博客网 时间:2024/05/01 08:41

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class ChannelInputStream extends InputStream {

  private ReadableByteChannel channel;

  public ChannelInputStream(ReadableByteChannel channel) throws IllegalArgumentException {
    if (channel == null) {
      throw new IllegalArgumentException("The readable byte channel is null");
    }

    this.channel = channel;
  }

  public int read() throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1);
    int result = channel.read(buffer);
    if (result != -1) {
      buffer.flip();
      result = (int) buffer.get();
      buffer.clear();
    }
    return result;
  }

  public int read(byte b[]) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(b.length);
    int result = channel.read(buffer);
    if (result != -1) {
      buffer.flip();
      buffer.get(b, 0, result);
      buffer.clear();
    }
    return result;
  }

  public int read(byte b[], int off, int len) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(b.length);
    int result = channel.read(buffer);
    if (result != -1) {
      buffer.flip();
      buffer.get(b, off, len > result ? result : len);
      buffer.clear();
    }
    return result;
  }

  public void close() throws IOException {
    channel.close();
  }
}

原创粉丝点击