java – How to use Protocol Buffer without files

Question:

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.
addressBook.addPerson(
  PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                   System.out));

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

Answer:

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();
addressBook.build().writeTo(baos);
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");         
addressBook.build().writeTo(conn.getOutputStream());

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