/Export.java Secret
Created
December 27, 2018 17:37
Converting java POJOs to/from bytes
This file contains 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
import java.io.*; | |
public class Export { | |
public static void writeTo(BufferedWriter writer, Person person) throws IOException { | |
writer.write(person.name); writer.newLine(); | |
writer.write(person.surname); writer.newLine(); | |
writer.write(person.age); | |
} | |
} |
This file contains 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
import java.io.*; | |
public class Import { | |
public static Person readFrom(BufferedReader reader) throws IOException { | |
Person p = new Person(); | |
p.name = reader.readLine(); | |
p.surname = reader.readLine(); | |
p.age = reader.read(); | |
return p; | |
} | |
} |
This file contains 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
public class Person { | |
public String name; | |
public String surname; | |
public int age; | |
public Person() {} | |
@Override | |
public String toString() { | |
return "{ name : " + name + ", surname : " + surname + ", age : " + age + " }"; | |
} | |
} |
This file contains 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
import java.io.*; | |
final String FILE_PATH = "person.data"; | |
// Export | |
try { | |
Person p = new Person(); | |
p.name = "John"; | |
p.surname = "Doe"; | |
p.age = 34; | |
BufferedWriter out = new BufferedWriter(new FileWriter(FILE_PATH)); | |
Export.writeTo(out, p); | |
out.close(); | |
System.out.println("Exported: " + p); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
// Import | |
try { | |
BufferedReader in = new BufferedReader(new FileReader(FILE_PATH)); | |
Person p = Import.readFrom(in); | |
in.close(); | |
System.out.println("Imported: " + p); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment