1package com.mkyong;
2
3package com.mkyong;
4
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.ObjectInputStream;
11import java.io.ObjectOutputStream;
12
13public class WriterReader {
14
15 public static void main(String[] args) {
16
17 Person p1 = new Person("John", 30, "Male");
18 Person p2 = new Person("Rachel", 25, "Female");
19
20 try {
21 FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
22 ObjectOutputStream o = new ObjectOutputStream(f);
23
24 // Write objects to file
25 o.writeObject(p1);
26 o.writeObject(p2);
27
28 o.close();
29 f.close();
30
31 FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
32 ObjectInputStream oi = new ObjectInputStream(fi);
33
34 // Read objects
35 Person pr1 = (Person) oi.readObject();
36 Person pr2 = (Person) oi.readObject();
37
38 System.out.println(pr1.toString());
39 System.out.println(pr2.toString());
40
41 oi.close();
42 fi.close();
43
44 } catch (FileNotFoundException e) {
45 System.out.println("File not found");
46 } catch (IOException e) {
47 System.out.println("Error initializing stream");
48 } catch (ClassNotFoundException e) {
49 // TODO Auto-generated catch block
50 e.printStackTrace();
51 }
52
53 }
54
55}