Java Reference
In-Depth Information
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.
17.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 17.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
17.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
try
(
// Create an output stream for file array.dat
output stream
10
ObjectOutputStream output =
new
ObjectOutputStream(
new
11
FileOutputStream(
"array.dat"
,
true
));
12 ) {
13
// Write arrays to the object output stream
store array
14
output.writeObject(numbers);
15
output.writeObject(strings);
16 }
17
18
try
(
// Create an input stream for file array.dat
19
ObjectInputStream input =
input stream
20
new
ObjectInputStream(
new
FileInputStream(
"array.dat"
));
21 ) {
22
int
[] newNumbers = (
int
[])(input.readObject());
restore array
23
String[] newStrings = (String[])(input.readObject());
24
25
// Display arrays
26
for
(
int
i =
0
; i < newNumbers.length; i++)
27 System.out.print(newNumbers[i] +
" "
);
28 System.out.println();
29
30
for
(
int
i =
0
; i < newStrings.length; i++)
31 System.out.print(newStrings[i] +
" "
);
32 }
33 }
34 }
1 2 3 4 5
John Susan Kim
Lines 14 and 15 write two arrays into file
array.dat
. Lines 22 and 23 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[]
.
17.25
✓
✓
What types of objects can be stored using the
ObjectOutputStream
? What is the
method for writing an object? What is the method for reading an object? What is the
return type of the method that reads an object from
ObjectInputStream
?
Check
Point
Search WWH ::
Custom Search