Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.nio.ByteBuffer;
import java.util.ArrayList;

public class Main {
    /**
     * Combine messages in an array and put a size header before each message
     * @param array
     * @return
     */
    public static byte[] compileMessages(ArrayList<byte[]> array) {

        int bufferSize = 0;
        for (int i = 0; i < array.size(); i++) {
            byte[] thisByte = array.get(i);
            bufferSize += (4 + thisByte.length);
        }

        byte[] buffer = new byte[bufferSize];

        int pointer = 0; // used to index the next empty byte to fill
        for (int i = 0; i < array.size(); i++) {
            int thisSize = array.get(i).length;
            System.arraycopy(ByteBuffer.allocate(4).putInt(thisSize).array(), 0, buffer, pointer, 4);
            System.arraycopy(array.get(i), 0, buffer, pointer + 4, thisSize);
            pointer += (4 + thisSize);
        }

        return buffer;
    }
}