output streams

39 views
Skip to first unread message

J.V.

unread,
Jul 2, 2009, 3:44:37 AM7/2/09
to Protocol Buffers
I'm trying to get the following to work but nothing is being written to
the output stream.
any ideas?

private void testEncode() throws Exception {
OutputStream out = new ByteArrayOutputStream();
CodedOutputStream cos = CodedOutputStream.newInstance(out);

Person.person.Builder person = Person.person.newBuilder();
person.setFirstName("First");
person.setLastName("Last");
person.build().writeTo(cos);
}

When I try to decode cos it throws an exception
Exception in thread "main"
com.google.protobuf.InvalidProtocolBufferException: Protocol message
contained an invalid tag (zero).

Kenton Varda

unread,
Jul 2, 2009, 12:53:55 PM7/2/09
to J.V., Protocol Buffers
You have to flush the CodedOutputStream.

You should just do this instead:

  byte[] data = person.build().toByteArray();

J.V.

unread,
Jul 2, 2009, 1:56:23 PM7/2/09
to Protocol Buffers
Thanks, for some reason I'm' getting the same error. If you have an
example of encoding to a stream and then decoding, it would be greatly
appreciated.
I will get it fully working and update the tutorial or post it somewhere
if desired.

thanks

jrv

Kenton Varda

unread,
Jul 2, 2009, 1:07:40 PM7/2/09
to J.V., Protocol Buffers
Write to a stream:

  message.writeTo(stream);

Parse from a stream:

  message = MyType.parseFrom(stream);

If you need to read/write multiple messages on the same stream (or the stream does not end immediately after the first message), use writeDelimitedTo() and parseDelimitedFrom().
Reply all
Reply to author
Forward
0 new messages