I learned about Google Protocol Buffers in recent days, Google Protocol Buffers are tools for serializing structured data, faster and smaller compared with xml and json, And also have the ablity of across language and plantform。
As Java Serialization has a lot of well-known problems especially when you need to share data with program written in c++ or other language,using protocol-buffers seems to be a good choice.
To use protocol-buffers, the first thing you need to do is to prepare a document named by xx.proto,this file is a definition of your structured dataand some Java Classes are generated base on the xx.proto file。
https://developers.google.com/protocol-buffers/docs/javatutorial
Here is a tutorial of protocol-buffers,more details could be find there ,and a file named addressbook.proto could be find there, take it as an example.next step is compiling the protocal files,if you don't compile the source code ,you can download the binary version which is suit for your plantform。 I'm using windows so I choose protoc-3.6.0-win32.zip,download and extract it,cd protoc-3.6.0-win32\bin dir which contain protoc.exe file and use commond like this:
protoc -I=C:\Users\wangxiaojiazu\Downloads\protoc-3.6.0-win32\bin --java_out=C:\Users\wangxiaojiazu\Downloads\protoc-3.6.0-win32\bin C:\Users\wangxiaojiazu\Downloads\protoc-3.6.0-win32\bin\addressbook.proto
if you excute the commond successfully,a directory contains some java classes will be generated,copy the class to your java project.meanwhile you need to add the dependance of protobuf-java to your project
that's all prepared,let's start write our code to serializing or unserializing.
public class Demo {
public static void main(String[] args) throws Exception {
writeDemo();
readDemo();
readAppendAndWriteDemo();
readDemo();
}
public static void writeDemo() throws IOException {
AddressBookProtos.AddressBook.Builder addressBook = AddressBookProtos.AddressBook.newBuilder(); addressBook.addPeople(buildPerson(new BufferedReader(new InputStreamReader(System.in)), System.out));
FileOutputStream output = new FileOutputStream("./AddressBook.txt");
addressBook.build().writeTo(output);
}
public static void readDemo() throws IOException {
AddressBookProtos.AddressBook addressBook = AddressBookProtos.AddressBook.parseFrom(new FileInputStream("./AddressBook.txt")); Print(addressBook);
}
public static void readAppendAndWriteDemo() throws IOException {
AddressBookProtos.AddressBook.Builder addressBookbuilder = AddressBookProtos.AddressBook.newBuilder(); addressBookbuilder.mergeFrom(new FileInputStream("./AddressBook.txt"));
addressBookbuilder.addPeople(buildPerson(new BufferedReader(new InputStreamReader(System.in)),System.out));
FileOutputStream output = new FileOutputStream("./AddressBook.txt");
addressBookbuilder.build().writeTo(output);
}
static void Print(AddressBookProtos.AddressBook addressBook) {
for (AddressBookProtos.Person person : addressBook.getPeopleList()) {
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 (AddressBookProtos.Person.PhoneNumber phoneNumber : person.getPhonesList()) {
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()); }
}
}
public static AddressBookProtos.Person buildPerson(BufferedReader stdin, PrintStream stdout) throws IOException { AddressBookProtos.Person.Builder person = AddressBookProtos.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;
}
AddressBookProtos.Person.PhoneNumber.Builder phoneNumber =AddressBookProtos.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(MOBILE);
}
else if (type.equals("home")) {
phoneNumber.setType(HOME);
}
else if (type.equals("work")) {
phoneNumber.setType(WORK);
}
else
{
stdout.println("Unknown phone type. Using default.");
}
person.addPhones(phoneNumber);
}
return person.build();
}
}