MCPcopy Index your code
hub / github.com/BruceEckel/OnJava8-Examples / main

Method main

serialization/MyWorld.java:24–76  ·  view source on GitHub ↗
(String[] args)

Source from the content-addressed store, hash-verified

22
23public class MyWorld {
24 public static void main(String[] args) {
25 House house = new House();
26 List<Animal> animals = new ArrayList<>();
27 animals.add(
28 new Animal("Bosco the dog", house));
29 animals.add(
30 new Animal("Ralph the hamster", house));
31 animals.add(
32 new Animal("Molly the cat", house));
33 System.out.println("animals: " + animals);
34 try(
35 ByteArrayOutputStream buf1 =
36 new ByteArrayOutputStream();
37 ObjectOutputStream o1 =
38 new ObjectOutputStream(buf1)
39 ) {
40 o1.writeObject(animals);
41 o1.writeObject(animals); // Write a 2nd set
42 // Write to a different stream:
43 try(
44 ByteArrayOutputStream buf2 =
45 new ByteArrayOutputStream();
46 ObjectOutputStream o2 =
47 new ObjectOutputStream(buf2)
48 ) {
49 o2.writeObject(animals);
50 // Now get them back:
51 try(
52 ObjectInputStream in1 =
53 new ObjectInputStream(
54 new ByteArrayInputStream(
55 buf1.toByteArray()));
56 ObjectInputStream in2 =
57 new ObjectInputStream(
58 new ByteArrayInputStream(
59 buf2.toByteArray()))
60 ) {
61 List
62 animals1 = (List)in1.readObject(),
63 animals2 = (List)in1.readObject(),
64 animals3 = (List)in2.readObject();
65 System.out.println(
66 "animals1: " + animals1);
67 System.out.println(
68 "animals2: " + animals2);
69 System.out.println(
70 "animals3: " + animals3);
71 }
72 }
73 } catch(IOException | ClassNotFoundException e) {
74 throw new RuntimeException(e);
75 }
76 }
77}
78/* Output:
79animals: [Bosco the dog[Animal@19e0bfd], House@139a55

Callers

nothing calls this directly

Calls 3

writeObjectMethod · 0.80
readObjectMethod · 0.80
addMethod · 0.45

Tested by

no test coverage detected