Protocol Buffers - 字串



概述

Protocol Buffers 字串會轉換為我們在使用的語言(例如 Java、Python 等)中的字串。繼續以劇院為例,以下是我們需要使用的語法,以便指示 Protocol Buffers 我們將要建立一個字串

theater.proto

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

message Theater {
   string name = 1;
   string address = 2;
}

現在,我們的類/訊息包含兩個字串屬性。它們每個也都有一個位置,這是 Protocol Buffers 在序列化和反序列化時使用的。成員的每個屬性都需要具有唯一的位置屬性。

從 Proto 檔案建立 Java 類

要使用 Protocol Buffers,我們現在必須使用protoc二進位制檔案從這個“.proto”檔案建立所需的類。讓我們看看如何做到這一點:

protoc  --java_out=. theater.proto

這將在當前目錄的com > tutorialspoint > theater資料夾中建立一個TheaterOuterClass.java類。我們在應用程式中使用此類,類似於在Protocol Buffers - 基本應用章節中所做的那樣。

使用從 Proto 檔案建立的 Java 類

首先,讓我們建立一個寫入器來寫入劇院資訊:

TheaterWriter.java

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()
         .setName("Silver Screener")
         .setAddress("212, Maple Street, LA, California")
         .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: \n" + theater);
   }
}	

接下來,我們將有一個讀取器來讀取劇院資訊:

TheaterReader.java

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);
      }
   }
}

編譯專案

現在我們已經設定了讀取器寫入器,讓我們編譯專案。

mvn clean install

序列化 Java 物件

現在,編譯後,讓我們先執行寫入器

java -cp .\target\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:
name: "Silver Screener"
address: "212, Maple Street, LA, California"

反序列化序列化物件

現在,讓我們執行讀取器從同一個檔案讀取:

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

Reading from file theater_protobuf_output
name: "Silver Screener"
address: "212, Maple Street, LA, California"

因此,正如我們所看到的,我們能夠透過將二進位制資料反序列化為Theater物件來讀取序列化的字串。現在讓我們在下一章Protocol Buffers - 數字中瞭解數字

廣告

© . All rights reserved.