2017-06-28 121 views
1

我是协议缓冲区的新手,所以我尝试了一个示例代码。我的原始文件代码如下:Java中的编码协议缓冲区

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

message Test1 { 
    required int32 a = 1; 
} 

我使用protec正确编译它。之后,我想在Java代码中使用它。代码是

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

现在我想在此实现编码,但我无法做到这一点。我在网上搜索并阅读了Google文档,但无法理解如何去做。有人能告诉我如何在这里执行基本编码吗?与protobufs中的编码有关的有用链接也被赞赏。
谢谢!

回答

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

然后

byte[] arr = obj.toByteArray(); 

obj.writeTo(outputStream); 
+0

如果非要进行解码,会是怎样的语法? – Aditya

+0

@Aditya'Test1.parseFrom'?请参阅https://developers.google.com/protocol-buffers/docs/javatutorial –

+0

如何以及在哪里查看生成的编码文件? – Aditya