集册 Java实例教程 在ByteBuffer上创建流

在ByteBuffer上创建流

欢马劈雪     最近更新时间:2020-01-02 10:19:05

487
在ByteBuffer上创建流

import java.io.IOException;
/**
NowJava.com - 时代Java
**/

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.ByteBuffer;


public class Main {

  public static void main(String[] args) {

    // Obtain a ByteBuffer; see Creating a ByteBuffer.

    ByteBuffer buf = ByteBuffer.allocate(10);


    // Create an output stream on the ByteBuffer

    OutputStream os = newOutputStream(buf);


    // Create an input stream on the ByteBuffer

    InputStream is = newInputStream(buf);


  }


  public static OutputStream newOutputStream(final ByteBuffer buf) {/**时代Java - nowjava.com**/

    return new OutputStream() {

      public synchronized void write(int b) throws IOException {

        buf.put((byte) b);

      }


      public synchronized void write(byte[] bytes, int off, int len)

          throws IOException {

        buf.put(bytes, off, len);

      }

    };

  }


  public static InputStream newInputStream(final ByteBuffer buf) {

    return new InputStream() {

      public synchronized int read() throws IOException {

        if (!buf.hasRemaining()) {

          return -1;

        }

        return buf.get();

      }


      public 
展开阅读全文