标签:http io 使用 java ar for 文件 sp on
碰巧用到Proto,算是笔记吧算是笔记吧,
windows :
1,两个文件:proto.exe, protobuf-java-2.4.1.jar
2,建立一个工程TestPb,在下面建立一个proto文件件,用来存放【。proto】文件
3,将proto,exe放在工程下,
4,建立一个msg.proto文件:
option java_package = "com.protobuftest.protobuf";
option java_outer_classname = "PersonProbuf";
message Person {
required string name = 1;
required int32 id = 2;
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;
message CountryInfo {
required string name = 1;
required string code = 2;
optional int32 number = 3;
}
}
message AddressBook {
repeated Person person = 1;
}
5,生成 java文件:在proto.exe目录下:protoc --java_out=./src ./proto/msg.proto
6,copy个测试示例了
新建一个文件TestPb.java
***********************************************************
package com.protobuftest.protobuf;
import java.util.List;
import com.google.protobuf.InvalidProtocolBufferException;
import com.protobuftest.protobuf.PersonProbuf;
import com.protobuftest.protobuf.PersonProbuf.Person;
import com.protobuftest.protobuf.PersonProbuf.Person.PhoneNumber;
public class TestPb {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonProbuf.Person.Builder builder = PersonProbuf.Person.newBuilder();
builder.setEmail("kkk@email.com");
builder.setId(1);
builder.setName("TestName");
builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("131111111").setType(PersonProbuf.Person.PhoneType.MOBILE));
builder.addPhone(PersonProbuf.Person.PhoneNumber.newBuilder().setNumber("011111").setType(PersonProbuf.Person.PhoneType.HOME));
Person person = builder.build();
byte[] buf = person.toByteArray();
try {
Person person2 = PersonProbuf.Person.parseFrom(buf);
System.out.println(person2.getName() + ", " + person2.getEmail());
List<PhoneNumber> lstPhones = person2.getPhoneList();
for (PhoneNumber phoneNumber : lstPhones) {
System.out.println(phoneNumber.getNumber());
}
} catch (InvalidProtocolBufferException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(buf);
}
}
***********************************************
*******************************
生成java文件:PersonProbuf.java
*******************************
工程文件结构:
标签:http io 使用 java ar for 文件 sp on
原文地址:http://www.cnblogs.com/dongweiq/p/3993439.html