java – How to use Protocol Buffer without files


There are examples where it is clearly shown how I can save data to a file and read it, I can’t understand how I can simply transfer this data, for example, simply by fixing it in a post, or simply transfer this class to another method.

AddressBook.Builder addressBook = AddressBook.newBuilder();

// Read the existing address book.
try {
  addressBook.mergeFrom(new FileInputStream(args[0]));
} catch (FileNotFoundException e) {
  System.out.println(args[0] + ": File not found.  Creating a new file.");

// Add an address.
  PromptForAddress(new BufferedReader(new InputStreamReader(,

// Write the new address book back to disk.
FileOutputStream output = new FileOutputStream(args[0]);;


Use not FileInputStream/FileOutputStream , but other I / O streams that are appropriate in your case. For example, they can be ByteArrayInputStream and ByteArrayOutputStream :

// пишем
ByteArrayOutputStream baos = new ByteArrayOutputStream();;
byte[] data = baos.toByteArray();

// читаем
AddressBook addressBook = AddressBook.parseFrom(new ByteArrayInputStream(data));

Or for example OutputStream HTTP connections:

HttpURLConnection conn = (HttpURLConnection) new URL("http://...").openConnection();
conn.setRequestMethod( "POST" );
conn.setRequestProperty("Content-Type", "application/octet-stream");;

However, for working with a byte array, the documentation offers ready-made methods:

byte[] toByteArray(); : serializes the message and returns a byte array.

static Person parseFrom(byte[] data); : parses a message from a byte array.

That is, something like:

// пишем
byte[] data = addressBook.toByteArray();

// читаем
addressBook = AddressBook.parseFrom(data);
Scroll to Top