Serialization

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later (possibly in a different computer environment).

This process of serializing an object is also called marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (also called unmarshalling).

Example Code

Worms.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.ObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Random;

public class Worm implements Serializable {

private int id;
private int size;

public Worm(int id, int size) {
this.id = id;
this.size = size;
}

public String toString() {
return "[" + id + "]: " + size;
}

public static void main(String[] args) throws ClassNotFoundException, IOException {
Random rand = new Random();
int number = 5;
String header = "Worms record";
Worm[] worms = new Worm[number];
for (int i = 0; i < 5; i++) {
worms[i] = new Worm(i, rand.nextInt(20));
}
System.out.println(header);
System.out.println(Arrays.toString(worms));

/*
* Using file (FileOutputStream & FileInputStream)
*
*/
// export to "worms.out" file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("worms.out"));
out.writeObject(header);
out.writeObject(worms);
out.close();

Worm[] wormsNew = new Worm[number];

// import from "worms.out" file
ObjectInputStream in = new ObjectInputStream(new FileInputStream("worms.out"));
String s = (String) in.readObject();
wormsNew = (Worm[]) in.readObject();
in.close();

System.out.println(s);
System.out.println(Arrays.toString(wormsNew));

/**
* Using byte array (ByteArrayOutputStream & ByteArrayInputStream)
*
*/
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out2 = new ObjectOutputStream(bout);
out2.writeObject(header);
out2.writeObject(worms);
out2.close();

ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
String s2 = (String) in2.readObject();
Worm[] wormsNew2 = new Worm[number];
wormsNew2 = (Worm[]) in2.readObject();
in2.close();

System.out.println(s2);
System.out.println(Arrays.toString(wormsNew2));

}
}

Comparison ByteArrayOutputStream vs FileOutputStream

  • ByteArrayOutputStream:
    Takes up memory space, but runs faster.

  • FileOutputStream:
    Save and load in local disk, takes longer to save and read.