您的位置:首页 > 编程语言 > Go语言

google protobuf 使用过程笔记

2016-09-29 00:00 681 查看
1、下载protobuf-2.5.0.tar.gz protoc-2.5.0-win32.zip
2、分别解压成文件夹A,文件夹B
3、将A中protoc.exe 复制到B中src目录下
4、在B/java路径 执行“mvn install”,生产jar包在target下
5、编写 一个test.proto文件

option java_package = "com.proto";
option java_outer_classname = "FirstProtobuf";
message TestBuf  {
required int32 ID = 1;
required string Url = 2;
}


6、利用protoc.exe 生成java文件(最好在protoc.exe所在目录进行,proto文件也在一起,在此执行则不用配置前者的环境变量):

protoc.exe --java_out=./ test.proto


7、测试(eclipse引入生成的java文件和jar包)

package com.test;

import java.io.IOException;
import com.proto.FirstProtobuf;
import com.proto.FirstProtobuf.TestBuf;

public class TestProtoBuf {

public static void main(String[] args) throws IOException {
//序列化过程
//FirstProtobuf是生成类的名字,即proto文件中的java_outer_classname
//testBuf是里面某个序列的名字,即proto文件中的message testBuf

FirstProtobuf.TestBuf.Builder builder = FirstProtobuf.TestBuf.newBuilder();

builder.setID( 123 );
builder.setUrl("http://www.test.com");

TestBuf info = builder.build();
byte[] buf = info.toByteArray();

TestBuf tb = TestBuf.parseFrom(buf);
System.out.println( tb.getID());
System.out.println( tb.getUrl());
//持久化过程
File file = new File(pathString + "test7.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"), 1024);
bw.write(Integer.toString(tb.getID()));
bw.write("\t");
bw.write(tb.getUrl());
bw.newLine();// 换行
bw.flush();
bw.close();
}
}


附上:

proto文件中的字段类型和java中的对应关系:
详见:https://developers.google.com/protocol-buffers/docs/proto
.proto Type java Type c++ Type
double double double
float float float
int32 int int32
int64 long int64
uint32
3ff0
int uint32
unint64 long uint64
sint32 int int32
sint64 long int64
fixed32 int uint32
fixed64 long uint64
sfixed32 int int32
sfixed64 long int64
bool boolean bool
string String string
bytes byte string

参考:
http://www.iteye.com/topic/1128881 http://blog.sina.com.cn/s/blog_653ac36d0101h9kn.html
现成jar包下载:
http://www.cnblogs.com/superbi/p/4368240.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  protobuf 序列化