Protocol Buffers:从文件中读取所有序列化消息

Protocol Buffers: reading all serialized messages from file

我正在尝试序列化和反序列化 protobuf 消息。按照 documentation 中的例子,我写:

ByteArrayOutputStream out = new ByteArrayOutputStream(...);
ArrayList<AddressBookProtos.Person> messages = ...;
for (int i = 0; i < messages.size; i++){
  messages.writeTo(out);
  out.flush();
}
out.close();

读回消息时,我希望这样写:

ByteArrayInputStream in = new ByteArrayInputStream(...);
ArrayList<AddressBookProtos.Person> messages = new ArrayList<...>();
while (in.available() > 0) {
   messages.add(AddressBookProtos.Person.parseFrom(in));
}

然而,我总是只返回一个结果。其他结果去哪儿了?

您必须使用 writeDelimitedTo/parseDelimitedFrom 或实施您自己的基于定界符的解决方案。

根据 javadoc:

... writes the size of the message as a varint before writing the data. This allows more data to be written to the stream after the message without the need to delimit the message data yourself. Use MessageLite.Builder.mergeDelimitedFrom(InputStream) (or the static method YourMessageType.parseDelimitedFrom(InputStream)) to parse messages written by this method.