1

考虑以下代码片段。

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()字符串的方法(应该能够再次解析)。

4

1 回答 1

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);
于 2017-11-10T04:38:49.693 回答