java中使用protobuf


http://blog.csdn.net/lan_liang/article/details/6632127

调研环境:windows


1.http://code.google.com/p/protobuf/downloads/list ,选择其中的win版本下载

2.下载一个protobuf-java-2.4.1.jar文件(注意,要与你刚才下的proto.exe版本不异,不然可能出现编译通不过现象)

http://grepcode.com/snapshot/repo1.maven.org/maven2/com.google.protobuf/protobuf-java/2.4.1


3.在proto.exe同级目录,编写一个msg.proto文件:


4.使用如下命令编译这个文件:


protoc.exe --java_out=./ msg.proto

5.将天生的ProtoBufferPractice.java文件引入eclipse

[java] view plaincopyprint?
  1. package Feinno.Practice.Learn;  
  2.   
  3. option java_package = "Fei尸兄nno.Practice.Learn";  
  4. option java_outer_classname = "ProtoBufferPractice";  
  5.   
  6. message msgInfo  {  
  7.   required int32 ID = 1;  
  8.   required int64 GoodID = 2;         
  9.   required string Url = 3;  
  10.   required string Guid = 4;  
  11.   required string Type = 5;  
  12.   required int32 Order = 6;  
  13. }  


6.把下载的protobuf-java-2.4.1.jar也引入工程

7.使用方法(序列化):

[java] view plaincopyprint?
  1. ProtoBufferPractice.msgInfo.Builder builder=ProtoBufferPractice.msgInfo.newBuilder();  
  2.     builder.setGoodID(100);  
  3.     builder.setGuid("11111-23222-3333-444");  
  4.     builder.setOrder(0);  
  5.     builder.setType("ITEM");  
  6.     builder.setID(10);  
  7.     builder.setUrl("http://xxx.jpg");  
  8.     ProtoBufferPractice.msgInfo info=builder.build();  
  9.   
  10.     byte[] result=info.toByteArray() ;  



8.反序列化:

[java] view plaincopyprint?
  1. try{  
  2.         ProtoBufferPractice.msgInfo msg = ProtoBufferPractice.msgInfo.parseFrom(result);  
  3.         System.out.println(msg);  
  4.     }  
  5.     catch(Exception ex){  
  6.         System.out.println(ex.getMessage());  
  7.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值