protobuf至關xml做用,可是比xml更加靈活,並且解析起了比xml方便,速度快java
第一步咱們能夠要protobuf的jar包工具
高手能夠本身下載源碼打jar包,菜鳥直接上網上下載個現成的jar(嘿嘿~我就是在網上直接下載的jar)ui
把jar包導入到項目裏面this
在上官網下載對應的protoc.exe編譯工具,copy到項目的src目錄下google
把.proto文件放到src目錄下xml
例如:ip
addressbook.protoget
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;
} input
如今打開命令窗口 進入項目的src目錄下源碼
執行命令 protoc --java_out=. addressbook.proto(注意.後面有個空格哦)
如今就生成了AddressBookProtos.java文件
好了如今咱們就寫個test 吧!
package com.example.tutorial;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.example.tutorial.AddressBookProtos.Person.PhoneNumber;
import com.example.tutorial.AddressBookProtos.Person.PhoneType;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.Descriptors.FieldDescriptor;
public class AddPersonTest {
public static void main(String[] args) throws Exception {
//序列化到文件
AddressBookProtos.Person.Builder builder = AddressBookProtos.Person
.newBuilder();
builder.setEmail("abc");
builder.setName("張三");
builder.setId(1);
//設置郵箱信息
PhoneNumber.Builder num = PhoneNumber.newBuilder();
num.setNumber("122");
num.setType(PhoneType.WORK);
builder.addPhone(num);
AddressBookProtos.Person model = builder.build();
byte[] result = model.toByteArray();
FileOutputStream out = new FileOutputStream(new File("E:/QQPCmgr/Desktop/person.xp"));
out.write(result);
out.flush();
out.close();
//反序列化到實體類
try{
FileInputStream input=new FileInputStream(new File("E:/QQPCmgr/Desktop/person.xp"));
byte[] result2=new byte[input.available()];
input.read(result2);
AddressBookProtos.Person msg = AddressBookProtos.Person.parseFrom(result2);
System.out.println(msg.getEmail()+msg.getPhone(0).getNumber());
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
解釋下
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";
第一個包名
第二個是類名
本人也是菜鳥 哈哈!在這個test還學到一點ArrayList集合,不能最沒有數據的狀況下set這樣會報 越界異常
由於ArrayList的set方法有個驗證
private void RangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); }