| SE450: Serialization: Basics [9/32] | ![]() ![]() ![]() |
An object which implements the Serializable
interface can be written and read from an
OutputStream and InputStream.
These stream objects must be wrapped inside either an
ObjectOutputStream or
ObjectInputStream.
These classes contain methods
writeObject(Object):void and
readObject():Object.
file:Main1.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
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
package serialization; import java.io.*; public class Main1 { public static void main(String args[]) { try { ObjectOutputStream os = new ObjectOutputStream (new FileOutputStream("out.dat")); os.writeObject(new Entry("Save Me", 1)); os.close(); ObjectInputStream is = new ObjectInputStream (new FileInputStream("out.dat")); Object o = is.readObject(); is.close(); Entry e = (Entry) o; System.out.println("Entry restored from file is: " + e.toString()); } catch (Exception e) { e.printStackTrace(); } } } class Entry implements Serializable { private static final long serialVersionUID = 2008L; private String message = ""; private int messageNumber = 0; public Entry(String message, int messageNumber) { this.message = message; this.messageNumber = messageNumber; } public String getMessage() { return message; } public int getMessageNumber() { return messageNumber; } public String toString() { return message + " " + Integer.toString(messageNumber); } }