Java ByteBuffer to InputStream newInputStream(final ByteBuffer buf)

Here you can find the source of newInputStream(final ByteBuffer buf)

Description

new Input Stream

License

Apache License

Declaration

public static InputStream newInputStream(final ByteBuffer buf) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;

import java.nio.ByteBuffer;

public class Main {
    public static InputStream newInputStream(final ByteBuffer buf) {
        return new InputStream() {
            public synchronized int read() throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }/*  w  w w  .jav a 2  s. c o m*/
                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());
                if (len == 0) {
                    return -1;
                } else {
                    buf.get(bytes, off, len);
                    return len;
                }
            }
        };
    }
}

Related

  1. newInputStream(final ByteBuffer buf)