Java ByteBuffer wrap as ReadableByteChannel
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.ReadableByteChannel; public class Main { public static ReadableByteChannel asReadableByteChannel( final ByteBuffer buffer) { return new ReadableByteChannel() { private boolean open = true; public int read(ByteBuffer dst) throws IOException { if (open == false) { throw new ClosedChannelException(); }//from w w w. j a va2 s.c o m final int p = buffer.position(); final int l = buffer.limit(); final int r = dst.remaining(); buffer.limit(p + r); dst.put(buffer); buffer.limit(l); return r; } public void close() throws IOException { open = false; } public boolean isOpen() { return open; } }; } } /** * Copyright (C) 2007 Sly Technologies, Inc. This library is free software; you * can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. This * library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */