2

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.

1 Answer 1

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

then

byte[] arr = obj.toByteArray();

or

obj.writeTo(outputStream); 
Sign up to request clarification or add additional context in comments.

3 Comments

How and where do I view the generated encoded file?
@Aditya well... where did you put it? (assuming there even is a file) - you either got an array, or you wrote to a stream. So... if the array: what did you do with it? if the stream: where was the stream pushing the data?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.