Protobuf - 布尔值

"bool"数据类型是 Protobuf 的基本构建块之一。它在我们使用的语言中转换为布尔值,例如 Java、Python 等。

继续使用 theater 示例,以下是我们需要的语法,以指示 Protobuf 我们将创建一个布尔属性 −

syntax = "proto3";
package theater;
option java_package = "com.tutorialspoint.theater";

message Theater {
   bool drive_in = 6;
}

现在我们的 message 类包含一个布尔属性。它还有一个 position,这是 Protobuf 在序列化和反序列化时使用的。成员的每个属性都需要分配一个唯一的编号。

要使用 Protobuf,我们现在必须使用 protoc 二进制文件从此".proto"文件创建所需的类。让我们看看如何做到这一点 −

protoc --java_out=java/src/main/java proto_files heater.proto

上述命令将创建所需的文件,现在我们可以在 Java 代码中使用它。首先让我们创建一个 writer 来写入 theater 信息 −

package com.tutorialspoint.theater;

import java.io.FileOutputStream;
import java.io.IOException;
import com.tutorialspoint.theater.TheaterOuterClass.Theater;

public class TheaterWriter {
   public static void main(String[] args) throws IOException {
      Theater theater = Theater.newBuilder()
         .setTotalCapcity(320)
         .setMobile(98234567189L)
         .setBaseTicketPrice(22.45f)
         .build();
		
      String filename = "theater_protobuf_output";
      System.out.println("Saving theater information to file: " + filename);
		
      try(FileOutputStream output = new FileOutputStream(filename)){
         theater.writeTo(output);
      }
      System.out.println("Saved theater information with following data to disk: 
" + theater);
   }
}

接下来,我们将有一个reader(阅读器)来读取theater(影院)信息−

package com.tutorialspoint.theater;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tutorialspoint.greeting.Greeting.Greet;
import com.tutorialspoint.theater.TheaterOuterClass.Theater;
import com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder;

public class TheaterReader{
   public static void main(String[] args) throws IOException {
      Builder theaterBuilder = Theater.newBuilder();

      String filename = "theater_protobuf_output";
      System.out.println("Reading from file " + filename);
        
      try(FileInputStream input = new FileInputStream(filename)) {
         Theater theater = theaterBuilder.mergeFrom(input).build();
         System.out.println(theater.getBaseTicketPrice());
         System.out.println(theater);
      }
   }
}

现在,编译后,让我们首先执行writer

> java -cp .	arget\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter

Saving theater information to file: theater_protobuf_output
Saved theater information with following data to disk:
drive_in: true

Now, let us execute the reader to read from the same file −

java -cp .	arget\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader

Reading from file theater_protobuf_output
drive_in: true

因此,正如我们所见,我们可以通过将二进制数据反序列化为 Theater 对象来读取序列化的布尔值。