public static ByteBuffer allocateAndReadAll ( int size , ReadableByteChannel channel ) throws IOException { ByteBuffer buf = ByteBuffer . allocate ( size ) ; int justRead ; int totalRead = 0 ; // FIXME, this will be a tight loop if the channel is non-blocking... while ( totalRead < size ) { logger . debug ( "reading totalRead={}" , totalRead ) ; if ( ( justRead = channel . read ( buf ) ) < 0 ) throw new EOFException ( "Unexpected end of stream after reading " + totalRead + " bytes" ) ; totalRead += justRead ; } buf . rewind ( ) ; return buf ; }
Allocate a buffer and fill it from a channel . The returned buffer will be rewound to the begining .