如何在内存中使用Protocol Buffers Serialized Data?

时间:2017-11-10 04:11:29

标签: java serialization protocol-buffers protobuf-java

请考虑以下代码段。

DynamicMessage message; // somehow I created the message
// Writing directly to file
message.writeTo(new FileOutputStream("out.ser"));
// Wrinting through other stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
BufferedWriter writer = new BufferedWriter(new FileWriter("out2.ser"));
writer.write(baos.toString());
writer.flush();
writer.close();

现在,如果我尝试使用

解析相同的文件
DynamicMessage message2 = DynamicMessage.parsefrom(descriptor, "out.ser"); // Works
DynamicMessage message3 = DynamicMessage.parsefrom(descriptor, "out2.ser"); // Doesn't Work

我认为在.toString()方法中已经改变了编码(可能)。任何人都可以建议一种方法将message.writeTo()序列化为一个字符串(应该能够再次解析)。

1 个答案:

答案 0 :(得分:0)

写给" out2.ser"由于您正在执行baos.toString()

,因此无效

protobuf的内容必须保存为字节数组。

修改下面的代码块

ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
BufferedWriter writer = new BufferedWriter(new FileWriter("out2.ser"));
writer.write(baos.toString());

作为

FileOutputStream f = new FileOutputStream("out2.ser");
message.writeTo(f);