Java Reference
In-Depth Information
number into the object stream. After the first time, only the serial number is stored if the
same object is written again. When the objects are read back, their references are the
same, since only one object is actually created in the memory.
19.6.2 Serializing Arrays
An array is serializable if all its elements are serializable. An entire array can be saved into a
file using
writeObject
and later can be restored using
readObject
. Listing 19.7 stores an
array of five
int
values and an array of three strings and reads them back to display on the
console.
L
ISTING
19.7
TestObjectStreamForArray.java
1
import
java.io.*;
2
3
public class
TestObjectStreamForArray {
4
public static void
main(String[] args)
5
throws
ClassNotFoundException, IOException {
6
int
[] numbers = {
1
,
2
,
3
,
4
,
5
};
7 String[] strings = {
"John"
,
"Susan"
,
"Kim"
};
8
9
// Create an output stream for file array.dat
output stream
10
11
12
13
ObjectOutputStream output =
new
ObjectOutputStream(
new
FileOutputStream(
"array.dat"
,
true
));
// Write arrays to the object output stream
14
15
16
17
// Close the stream
18 output.close();
19
20
output.writeObject(numbers);
store array
output.writeObject(strings);
// Create an input stream for file array.dat
21
22
23
24
25
26
27
// Display arrays
28
for
(
int
i =
0
; i < newNumbers.length; i++)
29 System.out.print(newNumbers[i] +
" "
);
30 System.out.println();
31
32
for
(
int
i =
0
; i < newStrings.length; i++)
33 System.out.print(newStrings[i] +
" "
);
34
35
// Close the stream
36 input.close();
37 }
38 }
ObjectInputStream input =
input stream
new
ObjectInputStream(
new
FileInputStream(
"array.dat"
));
int
[] newNumbers = (
int
[])(input.readObject());
restore array
String[] newStrings = (String[])(input.readObject());
1 2 3 4 5
John Susan Kim
Lines 14-15 write two arrays into file
array.dat
. Lines 24-25 read two arrays back in the
same order they were written. Since
readObject()
returns
Object
, casting is used to cast
the objects into
int[]
and
String[]
.