ProtoBufs简单样例


本工程列表如下:

.
├── classes
├── com
│   └── example
│       └── tutorial
│           ├── PersonProtos.java
│           └── ProtocolBufferExample.java
├── person.proto
└── protobuf-java-2.5.0.jar


1、编写消息格式文件person.proto

package tutorial;
option java_package="com.example.tutorial";
option java_outer_classname="PersonProtos";
message Person{
        required string name=1;
        required int32 id=2;
        optional string email=3;
        message PhoneNumber{
                required string number=1;
                optional int32 type=2;
        }
        repeated PhoneNumber phone=4;
}

执行:protoc --java_out=. person.proto生成相应的java类

2、编写ProtocolBufferExample.java

package com.example.tutorial;
import com.example.tutorial.PersonProtos.Person;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ProtocolBufferExample{
        static public void main(String[] args){
                Person p1=Person.newBuilder()
                        .setName("cklsoft")
                        .setEmail("cklsoft@gmail.com")
                        .setId(123456)
                        .addPhone(Person.PhoneNumber.newBuilder()
                                        .setNumber("01234567890")
                                        .setType(1)).build();
                try{
                        FileOutputStream out=new FileOutputStream("data.txt");
                        p1.writeTo(out);
                        out.close();
                }catch (Exception e){
                        System.out.println("Write Error!");
                }

                try{
                        FileInputStream in=new FileInputStream("data.txt");
                        Person p2=Person.parseFrom(in);
                        System.out.println("p2:"+p2);
                }catch(Exception e){
                        System.out.println("Read Error!");
                }
        }
}

执行javac -cp protobuf-java-2.5.0.jar -d classes/ com/example/tutorial/*.java


3、运行程序

java -cp .:../protobuf-java-2.5.0.jar com.example.tutorial.ProtocolBufferExample 


输出:

p2:name: "cklsoft"
id: 123456
email: "cklsoft@gmail.com"
phone {
  number: "01234567890"
  type: 1
}



相关内容

    暂无相关文章