Last active
September 21, 2015 18:43
-
-
Save Se7soz/3ca1ff5c5211e1d58fb2 to your computer and use it in GitHub Desktop.
Protocol buffer example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample; | |
import model.Model.*; | |
import java.io.*; | |
public class ProtocolBufferSample { | |
private static String DATA_SOURCE; | |
static { | |
DATA_SOURCE = String.format("%s/%s", System.getProperty("user.home"), "person.ser"); | |
} | |
public static OutputStream getOutputFileStream() throws IOException { | |
return new FileOutputStream(DATA_SOURCE); | |
} | |
public static InputStream getInputStream() throws IOException { | |
return new FileInputStream(DATA_SOURCE); | |
} | |
public void writeSamplePerson(String name, String email, int id) throws IOException { | |
Person person = Person.newBuilder().setName("Hussein Elsayed") | |
.setEmail("[email protected]") | |
.setId(1).build(); | |
OutputStream stream = ProtocolBufferSample.getOutputFileStream(); | |
person.writeTo(stream); | |
stream.close(); | |
} | |
public Person readSamplePerson() throws IOException { | |
InputStream stream = ProtocolBufferSample.getInputStream(); | |
Person person = Person.parseFrom(stream); | |
return person; | |
} | |
public static void main(String[] args) { | |
ProtocolBufferSample sample = new ProtocolBufferSample(); | |
try { | |
sample.writeSamplePerson("Hussein", "[email protected]", 1); | |
Person person = sample.readSamplePerson(); | |
System.out.println(person.getName()); | |
System.out.println(person.getEmail()); | |
System.out.println(person.getId()); | |
} | |
catch (Throwable th) { | |
th.printStackTrace(); // You should define a better way of logging | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment