[Edit]
+
0
-
0

Java - convert binary file to object

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
// Hint: the below solution uses embedded deserialization mechanysm in Java. import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; public class Program { public static void main(String[] args) throws IOException, ClassNotFoundException { User user; try ( FileInputStream fileStream = new FileInputStream("user.dat"); // user.dat was saved using https://dirask.com/snippets/jmJm21 ObjectInputStream objectStream = new ObjectInputStream(fileStream) ) { user = (User) objectStream.readObject(); } System.out.println("id: " + user.getId()); System.out.println("name: " + user.getName()); System.out.println("email: " + user.getEmail()); } public static class User implements Serializable { private static final long serialVersionUID = 1833276496243006152L; // embedded random number is used to identify object type private long id; private String name; private String email; public long getId() { return this.id; } public void setId(long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } } }