Aditya
Aditya

Reputation: 65

Encoding Protocol Buffers in Java

I am new to protocol buffers so I was trying out an example code. My proto file code is below:

syntax="proto2"; 
package test;  
option java_package="com.example.test";

message Test1 {
  required int32 a = 1;
} 

I compiled it using protec correctly. After that I wanted to use it out in a Java code. The code is

import com.example.test.Test1OuterClass;
import com.example.test.Test1OuterClass.Test1;
import java.io.*;
import java.util.*;

public class Testing {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");  
        int a = sc.nextInt();
        Test1.Builder t = Test1.newBuilder();
        t.setA(a).build();
    }  
} 

Now I want to implement encoding in this but I am not able to do it. I searched online and read the Google documentation but couldn't understand how to do it. Can someone tell me how to perform basic encoding here?

Useful links related to encoding in protobufs are appreciated too.

Upvotes: 2

Views: 1617

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062790

Test1 obj = t.setA(a).build();

then

byte[] arr = obj.toByteArray();

or

obj.writeTo(outputStream); 

Upvotes: 2

Related Questions