Java examples for java.nio:ByteBuffer
Concatenates one or more byte buffers to one large buffer.
//package com.java2s; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] argv) throws Exception { List bbs = java.util.Arrays.asList("asdf", "java2s.com"); System.out.println(concat(bbs)); }// w w w. jav a 2 s . c o m public static final ByteBuffer EMPTY = ByteBuffer.allocate(0); /** * Concatenates one or more byte buffers to one large buffer. The combined * size of all buffers must not exceed {@link java.lang.Integer#MAX_VALUE}. * * @param bbs list of byte buffers to combine * @return byte buffer containing the combined content of the supplied byte * buffers */ public static ByteBuffer concat(List<ByteBuffer> bbs) { long length = 0; // get amount of remaining bytes from all buffers for (ByteBuffer bb : bbs) { bb.rewind(); length += bb.remaining(); } if (length > Integer.MAX_VALUE) { throw new IllegalArgumentException( "Buffers are too large for concatenation"); } if (length == 0) { // very funny return EMPTY; } ByteBuffer bbNew = ByteBuffer.allocateDirect((int) length); // put all buffers from list for (ByteBuffer bb : bbs) { bb.rewind(); bbNew.put(bb); } bbNew.rewind(); return bbNew; } /** * Concatenates one or more byte buffers to one large buffer. The combined * size of all buffers must not exceed {@link java.lang.Integer#MAX_VALUE}. * * @param bb one or more byte buffers to combine * @return byte buffer containing the combined content of the supplied byte * buffers */ public static ByteBuffer concat(ByteBuffer... bb) { return concat(Arrays.asList(bb)); } }