高效的、可扩展的对结构化数据进行编码的格式规范
下面介绍的是使用Java ProtoBuf的基本步骤:
1. ,选择其中的win版本下载
2.下载一个protobuf-java-2.4.1.jar文件(注意,要与你刚才下的proto.exe版本相同,否则可能出现编译通不过现象)
3.在proto.exe同级目录,编写一个msg.proto文件:
package tutorial; option java_package = "com.protobuftest.protobuf"; option java_outer_classname = "PersonProbuf"; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; message CountryInfo { required string name = 1; required string code = 2; optional int32 number = 3; } } message AddressBook { repeated Person person = 1; }
4.使用如下命令编译这个文件:
5.将生成的ProtoBufferPractice.java文件引入eclipse
6.把下载的protobuf-java-2.4.1.jar也引入工程
7.使用方法:
import java.util.List;import com.google.protobuf.InvalidProtocolBufferException;import com.protobuftest.protobuf.PersonProbuf;import com.protobuftest.protobuf.PersonProbuf.Person;import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumber;import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumberOrBuilder;import com.protobuftest.protobuf.PersonProbuf.Person.PhoneType;public class ProtoBufTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub PersonProbuf.Person.Builder builder = PersonProbuf.Person.newBuilder(); builder.setEmail("kkk@email.com"); builder.setId(1); builder.setName("TestName"); builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder() .setNumber("131111111") .setType(PersonProbuf.Person.PhoneType.MOBILE)); builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder() .setNumber("011111") .setType(PersonProbuf.Person.PhoneType.HOME)); Person person = builder.build(); byte[] buf = person.toByteArray(); try { Person person2 = PersonProbuf.Person.parseFrom(buf); System.out.println(person2.getName() + ", " + person2.getEmail()); ListlstPhones = person2.getPhoneList(); for (PhoneNumber phoneNumber : lstPhones) { System.out.println(phoneNumber.getNumber()); } } catch (InvalidProtocolBufferException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(buf); }}
源文档 <>
原文链接: