首页 > 代码库 > (一)Java使用Protobuf

(一)Java使用Protobuf

学习使用Protobuf,创建java文件

windows :

步骤一:两个文件:proto.exe,  protobuf-Java-2.4.1.jar

步骤二:建立一个工程CreateProtoBuf,在下面建立一个proto文件件,用来存放【proto】文件

步骤三:将proto,exe放在工程下,

步骤四:建立一个msg.proto文件:

 1 option java_package = "com.protobuftest.protobuf"; 
 2 option java_outer_classname = "PersonProbuf"; 
 3  
 4 message Person 
 5 { 
 6   required string name = 1; 
 7   required int32 id = 2; 
 8   optional string email = 3; 
 9  
10   enum PhoneType 
11   { 
12     MOBILE = 0; 
13     HOME = 1; 
14     WORK = 2; 
15   } 
16  
17   message PhoneNumber
18   { 
19     required string number = 1; 
20     optional PhoneType type = 2 [default = HOME]; 
21   } 
22  
23   repeated PhoneNumber phone = 4; 
24  
25   message CountryInfo 
26   {
27           required string name = 1;
28           required string code = 2;
29           optional int32 number = 3;
30   }
31 } 
32  
33 message AddressBook
34  { 
35   repeated Person person = 1; 
36 } 

步骤五:生成 java文件:在proto.exe目录下:protoc  --java_out=./src   ./proto/msg.proto

步骤六:测试实例

 1 package com.protobuftest.protobuf;
 2  
 3 import java.util.List;
 4  
 5 import com.google.protobuf.InvalidProtocolBufferException;
 6 import com.protobuftest.protobuf.PersonProbuf;
 7 import com.protobuftest.protobuf.PersonProbuf.Person;
 8 import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumber;
 9  
10 public class Test
11 {
12     /**
13      * @param args
14      */
15     public static void main(String[] args) 
16     {
17         PersonProbuf.Person.Builder builder = PersonProbuf.Person.newBuilder();
18         builder.setEmail("xiaoxiangzi@email.com");
19         builder.setId(1);
20         builder.setName("筱灬湘子");
21         builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("1001").setType(PersonProbuf.Person.PhoneType.MOBILE));
22         builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("1002").setType(PersonProbuf.Person.PhoneType.HOME));
23          
24         Person person = builder.build();
25         byte[] buf = person.toByteArray();
26          
27         try 
28         {
29             Person person2 = PersonProbuf.Person.parseFrom(buf);
30             
31             System.out.println(person2.getName() + ", " + person2.getEmail());
32             
33             List<PhoneNumber> lstPhones = person2.getPhoneList();
34             
35             for (PhoneNumber phoneNumber : lstPhones)
36             {
37                 System.out.println(phoneNumber.getNumber());
38             }
39         } 
40         catch (InvalidProtocolBufferException e)
41         {
42             e.printStackTrace();
43         }
44          
45         System.out.println(buf);
46     }
47 }

工程目录如下:

技术分享 

(一)Java使用Protobuf