Protocol Buffer在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());
}


你可能感兴趣的:(Protocol_Buffer)