protocol buffer是一个高效的结构化数据存储格式,用来结构化数据的序列化与反序列化。目前支持java、c++、Python
相对于json而言:
数据量跟小
其他的还没看出什么优势
下载地址:
protobuf-2.5,protoc-2.5.0-win32.zip
安装过程:
1、进入解压后的java目录,查看readme.txt
2、把protoc.exe放入到protobuf-2.5中的
3、运行mvn -test
编写protocol buffer需要以下三步
1、定义消息格式文件,以proto结尾
package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "PersonProtos";
message Person{
required string name=1;
required int32 id=2;
optional string email=3;
message PhoneNumber{
required string number = 1;
optional int32 type=2;
}
repeated PhoneNumber phone=4;
}
2、使用编译器生成java文件
protoc --java_out=. person.proto
3、使用protocol buffer提供的api编写应用程序
package com.example.tutorial;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.example.tutorial.PersonProtos.Person;
import com.example.tutorial.PersonProtos.Person.PhoneNumber;
public class ProtocolBufferExample {
public static void main(String[] args) {
Person person = Person.newBuilder()
.setName("zhengqun")
.setEmail("717401115@qq.com")
.setId(111)
.addPhone(PhoneNumber.newBuilder().setNumber("15351506736").setType(1))
.addPhone(PhoneNumber.newBuilder().setNumber("17751544242").setType(2))
.build();
FileOutputStream out = null;
try {
out = new FileOutputStream("example.txt");
person.writeTo(out);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileInputStream in = null;
try {
in = new FileInputStream("example.txt");
Person p = Person.parseFrom(in);
System.out.println("person2:" + p);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
原文:http://www.cnblogs.com/zhengqun/p/4922783.html