Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol Buffers to file?

I am new to Protocol Buffers and seeing this as good approach to go. I created a proto file, and using compiler, I generated Java beans.

Using this Java Beans, I initialize the object, and try to write it to file. The purpose is just to see how big the file is. I don't have client/server test ready at this moment to test via HTTP. I am just trying to show my team at this point, how the request/response look like using protocol buffers.

Code I have is something like this:

=== Proto file ===

Profile {
  optional string name=1
  optional string id=2

  message DocGuids {
     required string docguids=3
  }

  repeated DocGuids docguids=4
}

=== Sample code ===

ProfileRequest.Builder profile = ProfileRequest.newBuilder();
profile.setName("John");
profile.setId("123");

for (int i=0;i<10;i++) {
 ProfileRequest.DocGuids.Builder docGuids = ProfileRequest.DocGuids.newBuilder();
 docGuids.setDocguid(GUID.guid()); 
     profile.addDocguids(docGuids);   
}

//write to disk
try {
    // Write the new address book back to disk.
   FileOutputStream output = new FileOutputStream("c:\\testProto.txt");
   DataOutputStream dos = new DataOutputStream(output);                  
       dos.write(profile.build().toByteArray());     
   dos.close();
   output.close();   
} catch (Exception e) {   
}

When I check testProto.txt, I saw the file was written as text file, not binary file, eventhough I use toByteArray.

Anyone could help?

Thanks

By the way, this is the code to read this file:

// Read from disk
FileInputStream input = new FileInputStream("c:\\testProto.txt");
DataInputStream dis = new DataInputStream(input);
profileBuild.mergeFrom(dis);
dis.close();
input.close()

I am able to read the object and get the value just fine, but just wondering if this is the correct approach to do?

like image 844
user373307 Avatar asked Feb 25 '26 04:02

user373307


1 Answers

I'm not sure why you're creating the DataOutputStream and calling dos.write in the first place...

I would normally use this:

profile.build().writeTo(output);

However, I would still have expected the file to be a binary file really. Sure, it would include the text "123" and "John" as those are just UTF-8 strings... but there should have been non-text in there as well. Are you sure it's just text? Could you post the output?

like image 139
Jon Skeet Avatar answered Feb 26 '26 20:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!