Creating a Stream on a ByteBuffer - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Creating a Stream on a ByteBuffer

Demo Code

import java.io.IOException;
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);

  }//  ww  w  .  ja va2s .  co m

  public static OutputStream newOutputStream(final ByteBuffer buf) {
    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 synchronized int read(byte[] bytes, int off, int len)
          throws IOException {
        // Read only what's left
        len = Math.min(len, buf.remaining());
        buf.get(bytes, off, len);
        return len;
      }
    };
  }
}

Related Tutorials