Protocol Buffer在Java中的应用

本文介绍了如何使用Python脚本批量生成Protobuf文件,并通过一个具体的示例展示了如何在项目中引入和使用这些生成的文件。涵盖了从编写消息定义、使用Protoc工具生成Java代码到在项目中实际应用的过程。

1.写好Message

package protoc;

message User {
	
	required int32 userid = 1;
	optional string username = 2;
}

2.利用PYTHON脚本批量生成

import os


CURRETN_PATH = os.getcwd()
IMPORT_PATH = CURRETN_PATH
DST_DIR = CURRETN_PATH 


java_command = ""
filelist = os.listdir(os.getcwd())
for file in filelist:
    suffix = file[file.rfind('.'):]
    out_file = file[:file.find('.')]
    if suffix == ".proto":
        command =  "protoc --proto_path=" + IMPORT_PATH + " --java_out=" + DST_DIR + " " + DST_DIR + "/" + file + " & "
        java_command += command


print ("Gen protocol start.")
os.system(java_command)
print ("Gen protocol complete.")

3.在项目中引入

/**
	 * 主函数
	 */
	public static void main(String[] args) throws Exception
	{
		final String path = "path.bin";
		OuterUser.User.Builder user = OuterUser.User.newBuilder()
				.setUserid(1)
				.setUsername("jack");
		
		FileOutputStream fos = new FileOutputStream(path);
		user.build().writeTo(fos);
		
		FileInputStream file = new FileInputStream(path);
		
		OuterUser.User.Builder user_in = OuterUser.User.newBuilder();
		user_in.mergeFrom(file);
		
		System.out.println("User ID: " + user_in.getUserid());
		System.out.println("User Name: " + user_in.getUsername());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值