I have a protobuf and want to encode its binary representation in base64 (or another textual encoding) for transmission over a text protocol. What's the cleanest way to do that?
The easiest option is to convert your proto to a byte[]
and then use Guava's BaseEncoding
class to encode those bytes as a base64 string:
String asBase64 = BaseEncoding.base64().encode(proto.toByteArray());
This is the most straightforward, but there are a number of other roughly equivalent mechanisms. For example if you want to write the encoded data to a file or other writable resource, you could write it to an OutputStream
returned by BaseEncoding.encodingStream()
:
proto.writeTo(BaseEncoding.base64().encodingStream(fileWriter));
As of Java 8 there's also java.util.Base64
, if you're not using Guava. See encode(byte[])
and wrap(OutputStream)
.
As Jon Skeet mentioned, proto3 can map to and from JSON if you don't explicitly need to transmit the data in binary format (and you're using proto3, of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With