Here you can find the source of infiniteReadableByteChannelFor(ByteBuffer... buffers)
Parameter | Description |
---|---|
buffers | The buffers to read frmo |
public static ReadableByteChannel infiniteReadableByteChannelFor(ByteBuffer... buffers)
//package com.java2s; /*//from www . j a va 2 s .c o m * Copyright (c) 2010 Matthew J. Francis and Contributors of the Bobbin Project * This file is distributed under the MIT licence. See the LICENCE file for further information. */ import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class Main { /** * Creates a ReadableByteChannel for a given byte array that does not report the end of the * stream * * @param bytes The byte array to create a ReadableByteChannel for * @return The created ReadableByteChannel */ public static ReadableByteChannel infiniteReadableByteChannelFor(byte[] bytes) { ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); final ReadableByteChannel byteChannel = Channels.newChannel(inputStream); ReadableByteChannel wrappedChannel = new ReadableByteChannel() { public int read(ByteBuffer dst) throws IOException { int bytesRead = byteChannel.read(dst); return bytesRead < 0 ? 0 : bytesRead; } public void close() throws IOException { } public boolean isOpen() { return true; } }; return wrappedChannel; } /** * Creates a ReadableByteChannel for a given list of ByteBuffers that does not report the end of * the stream * * @param buffers The buffers to read frmo * @return The created ReadableByteChannel */ public static ReadableByteChannel infiniteReadableByteChannelFor(ByteBuffer... buffers) { int totalSize = 0; for (ByteBuffer buffer : buffers) { totalSize += buffer.remaining(); } final ByteBuffer assembledBuffer = ByteBuffer.allocate(totalSize); for (ByteBuffer buffer : buffers) { assembledBuffer.put(buffer); } assembledBuffer.rewind(); ReadableByteChannel wrappedChannel = new ReadableByteChannel() { public int read(ByteBuffer dst) throws IOException { int bytesRead = Math.min(assembledBuffer.capacity() - assembledBuffer.position(), dst.remaining()); assembledBuffer.limit(assembledBuffer.position() + bytesRead); dst.put(assembledBuffer); return bytesRead; } public void close() throws IOException { } public boolean isOpen() { return true; } }; return wrappedChannel; } }