// Second, let's create a FlatBuffer from scratch in Java, and test it also.
// We use an initial size of 1 to exercise the reallocation algorithm,
// normally a size larger than the typical FlatBuffer you generate would be
// better for performance.
FlatBufferBuilder fbb = new FlatBufferBuilder(1);
// We set up the same values as monsterdata.json:
int str = fbb.createString("MyMonster");
int inv = Monster.createInventoryVector(fbb, new byte[] { 0, 1, 2, 3, 4 });
int fred = fbb.createString("Fred");
Monster.startMonster(fbb);
Monster.addName(fbb, fred);
int mon2 = Monster.endMonster(fbb);
Monster.startTest4Vector(fbb, 2);
Test.createTest(fbb, (short)10, (byte)20);
Test.createTest(fbb, (short)30, (byte)40);
int test4 = fbb.endVector();
int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
fbb.createString("test1"),
fbb.createString("test2")
});
Monster.startMonster(fbb);
Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
Color.Green, (short)5, (byte)6));
Monster.addHp(fbb, (short)80);
Monster.addName(fbb, str);
Monster.addInventory(fbb, inv);
Monster.addTestType(fbb, (byte)Any.Monster);
Monster.addTest(fbb, mon2);
Monster.addTest4(fbb, test4);
Monster.addTestarrayofstring(fbb, testArrayOfString);
int mon = Monster.endMonster(fbb);
Monster.finishMonsterBuffer(fbb, mon);
// Write the result to a file for debugging purposes:
// Note that the binaries are not necessarily identical, since the JSON
// parser may serialize in a slightly different order than the above
// Java code. They are functionally equivalent though.
try {
DataOutputStream os = new DataOutputStream(new FileOutputStream(
"monsterdata_java_wire.mon"));
os.write(fbb.dataBuffer().array(), fbb.dataBuffer().position(), fbb.offset());
os.close();
} catch(java.io.IOException e) {
System.out.println("FlatBuffers test: couldn't write file");
return;
}
// Test it:
TestBuffer(fbb.dataBuffer());
// Make sure it also works with read only ByteBuffers. This is slower,
// since creating strings incurs an additional copy
// (see Table.__string).
TestBuffer(fbb.dataBuffer().asReadOnlyBuffer());
TestEnums();
System.out.println("FlatBuffers test: completed successfully");
}