Protobuf 简介

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("dsfs@qq.com")
				.addPhone(Person.PhoneNumber.newBuilder()
						.setNumber("12321324234")
						.setType(Person.PhoneType.HOME).build())
				.build();
		person.writeDelimitedTo(new FileOutputStream("D:/tmp/address.data"));	
	}

}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_26182553

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值