FlatBuffers - 默认值



概述

我们已经在之前的例子中看到了如何序列化和反序列化FlatBuffers中的各种类型。如果没有指定任何值,则会存储默认值。如果我们为变量指定相同的默认值,则FlatBuffers不会分配额外的空间。

FlatBuffers根据下表支持其数据类型的默认值:

数据类型 默认值
int16 / short / int / long 0
Float/double 0.0
字符串 空字符串
布尔值 False
枚举 第一个枚举项,即“index=0”的项
向量 空列表
嵌套类 null

因此,如果未指定这些数据类型的数据,则它们将采用上述默认值。现在,让我们继续我们的剧院示例来演示其工作原理。

在这个例子中,我们将让所有字段都使用默认值。唯一指定的字段将是剧院的名称。

继续我们来自Flat Buffers - 字符串章节的剧院示例,以下是我们需要使用的语法,以指示FlatBuffers我们将创建各种数据类型:

theater.fbs

namespace com.tutorialspoint.theater;

enum PAYMENT_SYSTEM: int { CASH = 0, CREDIT_CARD = 1, DEBIT_CARD, APP = 3 }

table Theater {
   name:string;
   address:string;
   
   total_capacity:short;
   mobile:int;
   base_ticket_price:float;
   
   drive_in:bool;
   
   payment:PAYMENT_SYSTEM;
   
   snacks:[string];
   
   owner: TheaterOwner;
}

table TheaterOwner {
	name:string;
	address:string;
}
root_type Theater;

现在我们的剧院表格包含多个属性。

从fbs文件创建Java类

要使用FlatBuffers,我们现在必须使用flatc二进制文件从此“.fbs”文件创建所需的类。让我们看看如何做到这一点:

flatc --java theater.fbs

这将在当前目录的com > tutorialspoint > theater文件夹中创建一个Theater、TheaterOwner和PAYMENT_SYSTEM类。我们在应用程序中使用此类,就像在Flat Buffers - Schema章节中所做的那样。

使用从fbs文件创建的Java类

TheaterWriter.java

package com.tutorialspoint.theater;

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

import com.google.flatbuffers.FlatBufferBuilder;

public class TheaterWriter {
   public static void main(String[] args) throws FileNotFoundException, IOException {
      // create a flat buffer builder
      // it will be used to create Theater FlatBuffer
      FlatBufferBuilder builder = new FlatBufferBuilder(1024);
      
      // create offset for name
      int name = builder.createString("Mery");
      
      // create theater FlatBuffers using startTheater() method
      Theater.startTheater(builder);
      // add details to the Theater FlatBuffer
      Theater.addName(builder, name);      
      
      // mark end of data being entered in Greet FlatBuffer
      int theater = Theater.endTheater(builder);

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

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

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

接下来,我们将有一个读取器来读取剧院信息:

TheaterReader.java

package com.tutorialspoint.theater;

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

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

      String filename = "theater_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
         Theater theater = Theater.getRootAsTheater(buf);

         // print theater values 
         System.out.println("Name: " + theater.name());
         System.out.println("Address: " + theater.address());
         System.out.println("Total Capacity: " + theater.totalCapacity());
         System.out.println("Mobile: " + theater.mobile());
         System.out.println("Base Ticket Price: " + theater.baseTicketPrice());
         System.out.println("Drive In: " + theater.driveIn());
         System.out.println("Snacks: ");
         if(theater.snacksLength() != 0) {
            for(int i = 0; i < theater.snacksLength(); i++ ) {
               System.out.print(" " + theater.snacks(i));
            } 
         }else {
            System.out.println("Snacks are empty.");
         }

         System.out.println("Payment Method: " + PAYMENT_SYSTEM.name(theater.payment()));        
         System.out.println("Owner Details: ");
         TheaterOwner owner = theater.owner();
         if(owner != null) {
            System.out.println("Name: " + owner.name());
            System.out.println("Address: " + owner.address());        	 
         }else {
            System.out.println("Owner " + owner);
         }        
      }
   }
}

编译项目

现在我们已经设置了读取器写入器,让我们编译项目。

mvn clean install

序列化Java对象

现在,编译后,让我们首先执行写入器

java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter

Saving theater to file: theater_flatbuffers_output
Saved theater with following data to disk:
20

反序列化已序列化的对象

现在,让我们执行读取器从同一文件中读取:

java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader

Reading from file theater_flatbuffers_output
Name: Mery
Address: null
Total Capacity: 0
Mobile: 0
Base Ticket Price: 0.0
Drive In: false
Snacks:
Snacks are empty.
Payment Method: CASH
Owner Details:
Owner null

因此,正如我们所看到的,我们能够通过将二进制数据反序列化为剧院对象来读取默认值。

广告
© . All rights reserved.