Protocol Buffer入门——搭建环境(JAVA版)

Protocol Buffers简介:

Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,很适合做数据存储或 RPC 数据交换格式。它可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。

Protocol Buffers环境搭建(JAVA):

准备:下载protobuf-java-2.5.0.zip(里面包含protobuf-java-2.5.0.jar和protoc.exe编辑器)

步骤:

1.新建java工程test_protobufers

2.导入protobuf-java-2.5.0.jar,并将protoc.exe编辑器放到test_protobufers项目工程根目录下。

3.test_protobufers项目工程根目录下创建proto文件夹,用于存放.proto的文件。

4.编写Message放到proto文件夹下,引用官网的例子,创建addressbook.proto代码如下:

package tutorial;
option java_package = "com.example.tutorial";//编译后生成的文件存放的位置
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;
}

5. 编译addressbook.proto成指定的java类, 命令行下进入编译器所在目录,执行如下命令:

     protoc -I=proto/ --java_out=src proto/addressbook.proto

其中,src为生成的java类的目标位置,这里我们选择项目的默认包,proto/addressbook.proto表示我们的proto文件,运行后即生成java类,生成的java类被放在了package com.example.tutorial中。与上面代码中option java_package 指定的参数有关系。

6.现在有了生成的AddressBookProtos.java类,我们可以向文件里写入消息了,首先编写AddPerson.java,代码如下:

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person; 
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; 
import java.io.InputStreamReader;  
import java.io.IOException;  
import java.io.PrintStream;    
class AddPerson{    
	// 这个函数将会根据用户的输入填充一个用户的信息  
	static Person PromptForAddress(BufferedReader stdin,PrintStream stdout)throws IOException{      
		Person.Builder person = Person.newBuilder();
		stdout.print("Enter person ID: ");      
		person.setId(Integer.valueOf(stdin.readLine()));        
		stdout.print("Enter name: ");      
		person.setName(stdin.readLine());        
		stdout.print("Enter email address (blank for none): ");      
		String email = stdin.readLine();      
		if (email.length() > 0){        
			person.setEmail(email);     
		}       
		while (true){        
			stdout.print("Enter a phone number (or leave blank to finish): ");
			String number = stdin.readLine();        
			if (number.length() == 0){          
				break;        
			}          
			Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber.newBuilder().setNumber(number);
			stdout.print("Is this a mobile, home, or work phone? ");        
			String type = stdin.readLine();        
			if (type.equals("mobile")){          
				phoneNumber.setType(Person.PhoneType.MOBILE);    
			} else if (type.equals("home")) {          
				phoneNumber.setType(Person.PhoneType.HOME);        
			} else if (type.equals("work")) {         
				phoneNumber.setType(Person.PhoneType.WORK);        
			} else {          
				stdout.println("Unknown phone type.  Using default.");        
			}          
			person.addPhone(phoneNumber);      
		}        
		return person.build();    
	}      
	// Main function: Reads the entire address book from a file,  adds one person based on user input, 
	//then writes it back out to the same file.    
	public static void main(String[] args) throws Exception{      
		if (args.length != 1) {        
			System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");        
			System.exit(-1);      
		}        
		AddressBook.Builder addressBook = AddressBook.newBuilder();        
		// Read the existing address book.      
		try {        
			addressBook.mergeFrom(new FileInputStream(args[0]));      
		} catch (FileNotFoundException e) {        
			System.out.println(args[0] + ": File not found.  Creating a new file.");      
		}        
		// Add an address.      
		addressBook.addPerson(        
			PromptForAddress(new BufferedReader(new InputStreamReader(System.in)), System.out));        
		// Write the new address book back to disk.      
		FileOutputStream output = new FileOutputStream(args[0]);      
		addressBook.build().writeTo(output);     
		output.close();    
	} 
}
7. 首先配置参数,也就是消息被序列化后存储的文件名,这里,我们就把参数设置成AddressBook。运行时如果文件不存在,将会创建文件并写入;如果存在,就写入。运行程序,按照提示输入消息。然后查看我们的项目路径下,将会产生AddressBook文件。(AddressBook可以换成自己想要的名字。
8. 上一步是将消息序列化到文件中,这一步将文件中的消息反序列化,类似地,我们创建一个类:ListPeople.java 代码如下:

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.FileInputStream;

public class ListPeople {
	// Iterates though all people in the AddressBook and prints info about them.
	static void Print(AddressBook addressBook) {
		for (Person person : addressBook.getPersonList()) {
			System.out.println("Person ID: " + person.getId());
			System.out.println("  Name: " + person.getName());
			if (person.hasEmail()) {
				System.out.println("  E-mail address: " + person.getEmail());
			}
			for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
				switch (phoneNumber.getType()) {
				case MOBILE:
					System.out.print("  Mobile phone #: ");
					break;
				case HOME:
					System.out.print("  Home phone #: ");
					break;
				case WORK:
					System.out.print("  Work phone #: ");
					break;
				}
				System.out.println(phoneNumber.getNumber());
			}
		}
	}

	// Main function: Reads the entire address book from a file and prints all
	// the information inside.
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");
			System.exit(-1);
		}
		// Read the existing address book.
		AddressBook addressBook = AddressBook.parseFrom(new FileInputStream(
				args[0]));
		Print(addressBook);
	}
}
输入参数AddressBook(第7步中设置的参数)并运行程序,将会看到我们输入的消息体被遍历并打印出来了!


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值