split input buffer in chunks of maxsize. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

split input buffer in chunks of maxsize.

Demo Code


import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Iterator;
import org.apache.log4j.Logger;

public class Main{
    /**/*from  www  .  j a v a 2  s .  co m*/
     * split inputbuffer in chunks of maxsize. Several maxsize values may be
     * given, in which case these are used in turn, and the last is repeated
     * until input is empty. For example, if maxsize = { 1, 5, 4 }, the first
     * returned buffer will have size 1, the second 5 and any subsequent buffers
     * will have size 4, except the last one which is size 4 or smaller.
     * 
     * @param in
     * @param maxsize list of buffer sizes
     * @return Iterable which returns a ByteBuffer-iterator iterating through
     *         the split buffers.
     */
    final static public Iterable<ByteBuffer> splitAndIterate(
            final ByteBuffer in, final int... maxsize) {
        return new Iterable<ByteBuffer>() {
            @Override
            public Iterator<ByteBuffer> iterator() {
                return new Iterator<ByteBuffer>() {
                    boolean hasNext = true;
                    int i = 0;

                    @Override
                    public boolean hasNext() {
                        return hasNext;
                    }

                    @Override
                    public ByteBuffer next() {
                        ByteBuffer out;
                        if (in.remaining() <= maxsize[i]) {
                            hasNext = false;
                            out = in.slice();
                        } else {
                            out = slicePosToLength(in, maxsize[i]);
                        }
                        if (i + 1 < maxsize.length) {
                            i++;
                        }
                        return out;
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
    /**
     * Returns a slice of the bytebuffer starting at the current position and with the given length.
     * Updates position the the first position not included in returned buffer.
     * 
     * @param buf
     * @param length
     * @return
     */
    final static public ByteBuffer slicePosToLength(ByteBuffer buf,
            int length) {
        int lim = buf.limit();
        int end = buf.position() + length;
        buf.limit(end);
        ByteBuffer save = buf.slice();
        buf.position(end);
        buf.limit(lim);
        return save;
    }
}

Related Tutorials