Flat Buffers - Schema



Overview

Let us now use Google Flat Buffers and see how it works with a simple Greeting app. In this example, we will create a simple application which would do the following −

Greeting Writer

  • Take greeting and username from the user

  • Store the above information in a file in the disk

Greeting Reader

  • Reads the same file which we stored in the above file

  • Convert that data into an object and print the data

Flat Buffers Schema file

The flat buffers "schema file" contains the schema definition of the data we want to serialize. The data is stored in a human readable file with the extension ".fbs".

Let us store the following data in greeting.fbs and we will use this in our first application.

greeting.fbs

namespace com.tutorialspoint.greeting;

table Greet {
   greeting: string;
   username: string;
}

root_type Greet;

Understanding each construct

namespace com.tutorialspoint.greeting;

The namespace here is used for package/namespace declaration for the generated code from the .fbs file. For example, our generated java classes will be lying in com.tutorialspoint.greeting package.

table Greet

Name of the base class for the object which would be created/recreated.

greeting: string;
username: string;

These are the attributes of the Greet class along with the data type.

root_type Greet;

root_type tells the flat buffers compiler about the root table which is Greet and will be the main class while generating code.

Flat Buffers Code Generation

Now that we have defined, let us install the "flatc" binary which we will use to autogenerate the code for the above Greet class. The binaries can be found at "https://github.com/google/flatbuffers/releases".

Choose the correct binary based on the OS. We will install flat buffers compiler binary on Windows but the steps are not very different for Linux.

We've downloaded https://github.com/google/flatbuffers/releases/download/v25.2.10/Windows.flatc.binary.zip

Verify Flat Buffers Compiler Setup

Once installed, ensure that you are able to access it via command line −

flatc --version

flatc version 25.2.10

It confirms that Flatc is correctly installed. Now let us move to creating the Greeting app described above for Java.

Greeting App in Java

Now that we have installed flatc, we can auto-generate the code from the fa files using flatc. Let us first create a Java project though.

Following is the Maven configuration that we will use for our Java project. Note that it contains the required library for flatc-java as well.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint.greeting</groupId>
   <artifactId>flatbuffers-tutorial</artifactId>
   <version>1.0</version>
   <packaging>jar</packaging>

   <properties>
      <maven.compiler.source>21</maven.compiler.source>
      <maven.compiler.target>21</maven.compiler.target>
   </properties>

   <dependencies>
      <!-- https://mvnrepository.com/artifact/com.google.flatbuffers/flatbuffers-java -->
      <dependency>
         <groupId>com.google.flatbuffers</groupId>
         <artifactId>flatbuffers-java</artifactId>
         <version>25.2.10</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.4</version>
            <configuration>
               <!--Put your configurations here-->
            </configuration>
            <executions>
               <execution>
                  <phase>package</phase>
                     <goals>
                     <goal>shade</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

All of our code would be present under src/main/java.

With the project structure out of the way, let us generate the code for the Greet class −

Generate Java Classes

flatc --java greeting.fbs

Post execution of the command, you will notice a auto-generated class under com > tutorialspoint > greeting folder within current directory.

  • Greet.java

This file contains a class Greet which would help us with serialization and deserialization of the Greet object.

Using Generated Java Classes

Now, let us write the writer of the data, which will take the username and the greeting as its inputs −

GreetWriter.java

package com.tutorialspoint.greeting;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.google.flatbuffers.FlatBufferBuilder;

public class GreetWriter {
   public static void main(String[] args) throws FileNotFoundException, IOException {
      // create a flat buffer builder
      // it will be used to create Greet FlatBuffer
      FlatBufferBuilder builder = new FlatBufferBuilder(1024);

      // read greeting and username from console
      int greeting = builder.createString(args[0]);
      int username = builder.createString(args[1]);

      // create Greet FlatBuffers using startGreet() method
      Greet.startGreet(builder);
      // add the greeting and username to the Greet FlatBuffer
      Greet.addGreeting(builder, greeting);
      Greet.addUsername(builder, username);

      // mark end of data being entered in Greet FlatBuffer
      int greet = Greet.endGreet(builder);

      // finish the builder
      builder.finish(greet);

      // get the bytes to be stored
      byte[] data = builder.sizedByteArray();

      String filename = "greeting_flatbuffers_output";
      System.out.println("Saving greeting to file: " + filename);
      // write the builder content to the file named	greeting_flatbuffers_output
      try(FileOutputStream output = new FileOutputStream(filename)){
         output.write(data);
      }
      System.out.println("Saved greeting with following data to disk: \n" + greeting);
   }   
}

The writer simply takes CLI arguments, creates the Greet object, serializes it and then dumps it to a file.

Now let us write a reader which will read the file −

GreetReader.java

package com.tutorialspoint.greeting;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

public class GreetReader {
   public static void main(String[] args) throws FileNotFoundException, IOException {

      String filename = "greeting_flatbuffers_output";
      System.out.println("Reading from file " + filename);

      try(FileInputStream input = new FileInputStream(filename)) {
         // get the serialized data
         byte[] data = input.readAllBytes();
         ByteBuffer buf = ByteBuffer.wrap(data);
         // read the root object in serialized data
         Greet greet = Greet.getRootAsGreet(buf);

         // print greet values 
         System.out.println("Greeting: " + greet.greeting() + "\n" + "Username: " + greet.username());
      }
   }
}

The reader simply reads from the same file, deserializes it, and prints the data about the greeting.

Compile the project

Now that we have set up the reader and the writer, let us compile the project.

mvn clean install

Serialize the Java Object

And now, let us first execute the writer to serialize an object to file system.

java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.greeting.GreetWriter Hello John

Saving greeting to file: 
greeting_protobuf_output

Saved greeting with following data to disk:
12

Deserialize the Serialized Object

And then, let us execute the reader to deserialize an object from file system.

java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.greeting.GreetReader

Reading from file greeting_protobuf_output
Greeting: Hello
Username: John

So, as we see the data that was serialized by the writer and saved to the file, that exact data is correctly deserialized by the reader and printed accordingly.

Advertisements