java use protobuffer

来源:互联网 发布:燃气灶烤箱一体机 知乎 编辑:程序博客网 时间:2024/06/05 23:41

一、创建proto文件

package cn.proto;option java_package="cn.proto";option java_outer_classname = "Test";option optimize_for = SPEED;message TestUser{    optional  int64 id = 1;    optional string name=2;}

二、自动生成Test文件,使用maven编译生成

三、测试写入和读出

package cn.useproto;import cn.proto.Test;import java.io.*;/** * Created by sz0816 on 14-5-1. */public class TestProto {    public static void main(String []args) throws IOException {        TestProto testProto = new TestProto();        testProto.testWrite();        testProto.testRead();    }    public void testWrite() throws IOException {        Test.TestUser.Builder testBuilder = Test.TestUser.newBuilder();        testBuilder.setId(12);        testBuilder.setName("yezi");        Test.TestUser testUser = testBuilder.build();        File file  = new File("C:\\Users\\sz0816\\Desktop\\test.dat");        FileOutputStream fileOutputStream = new FileOutputStream(file);        fileOutputStream.write(testUser.toByteArray());        fileOutputStream.flush();        fileOutputStream.close();    }    public void testRead()throws IOException{        File file  = new File("C:\\Users\\sz0816\\Desktop\\test.dat");        Test.TestUser testUser = Test.TestUser.parseFrom(new FileInputStream(file));        System.out.println(testUser.getId() + "-->" + testUser.getName());    }}

四、部分解释

1、如果想使用对象数据

message TestUser{    optional  int64 id = 1;    optional string name=2;    optional TestTeacher testTeacher=3;}

message TestTeacher{   optional int32 id=1;   optional string name=2;   optional TestUser testUser=3;}

2、如果使用List对象


message TestUser{    optional  int64 id = 1;    optional string name=2;    optional TestTeacher testTeacher=3;}message TestTeacher{   optional int32 id=1;   optional string name=2;   repeated TestUser testUser=3; //相当list}

3、字段解析

equired:一个格式良好的消息一定要含有1个这种字段。表示该值是必须要设置的;
optional:消息格式中该字段可以有0个或1个值(不超过1个)。
repeated:在一个格式良好的消息中,这种字段可以重复任意多次(包括0次)。重复的值的顺序会被保留。表示该值可以重复,相当于java中的List。



0 0
原创粉丝点击