1. 下载编译文件:protoc-2.6.0-win32.zip
https://sourceforge.net/projects/protobuf/?source=typ_redirect
2. 导入开发包
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.6.1</version>
</dependency>
3. 编写Message文件
addressbook.proto
// See README.txt for information and build instructions. package tutorial; option java_package = "org.hdp.practice.serial"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; // Unique ID number for this person. 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; } // Our address book file is just one of these. message AddressBook { repeated Person person = 1; }
4. 编译Message文件
protoc --java_out=. addressbook.proto
生成:AddressBookProtos.java文件,将此文件复制到包路径org.hdp.practice.serial下
5.编写序列化和反序列化代码测试代码
public class SerializationByProtobuf { public static void main(String[] args) throws Exception{ writeProtobuf(); //readProtobuf(); } static void readProtobuf() throws Exception{ Person person = Person.parseDelimitedFrom(new FileInputStream("D:/tmp/address.data")); System.out.println(person.getEmail()); } static void writeProtobuf() throws Exception{ Person person = Person.newBuilder() .setId(1) .setName("tom") .setEmail("[email protected]") .addPhone(Person.PhoneNumber.newBuilder() .setNumber("12321324234") .setType(Person.PhoneType.HOME).build()) .build(); person.writeDelimitedTo(new FileOutputStream("D:/tmp/address.data")); } }