Java ByteBuffer wrap as OutputStream

Description

Java ByteBuffer wrap as OutputStream

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class Main {
  /**/*from   w  w w  .  j a  v  a2s.c o m*/
   * Returns an output stream for a ByteBuffer. The write() methods use the
   * relative ByteBuffer put() methods.
   */
  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);
      }
    };
  }
}



PreviousNext

Related