Java tutorial
//package com.java2s; //License from project: Apache License public class Main { /** * Fragments a byte buffer into smaller fragments of (max.) frag_size. * Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments * of 248 bytes each and 1 fragment of 32 bytes. * @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size = 0; byte[] fragment; int tmp_size = 0; int num_frags; int index = 0; num_frags = length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval = new byte[num_frags][]; while (accumulated_size < length) { if (accumulated_size + frag_size <= length) tmp_size = frag_size; else tmp_size = length - accumulated_size; fragment = new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++] = fragment; accumulated_size += tmp_size; } return retval; } }