navige navige - 1 month ago 6x
Java Question

Protocol Buffers: reading all serialized messages from file

I am trying to serialize and deserialize protobuf messages. Following the example from the documentation, I write:

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

When reading the messages back in, I would expect to write:

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

However, I always get only one result back in. Where are the other results gone?


You have to use writeDelimitedTo/parseDelimitedFrom or implement your own delimiter-based solution.

According to 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.