Java Reference
In-Depth Information
64
// set balance
65
public void
setBalance(
double
balance)
66
{
67
this
.balance = balance;
68
}
69
70
// get balance
71
public double
getBalance()
72
{
73
return
balance;
74
}
75
}
// end class Account
Fig. 15.9
|
Account
class for serializable objects. (Part 3 of 3.)
In a
Serializable
class, every instance variable must be
Serializable
. Non-
Seri-
alizable
instance variables must be declared
transient
to indicate that they should be
ignored during the serialization process.
By default, all primitive-type variables are serializ-
able.
For reference-type variables, you must check the class's documentation (and possibly
its superclasses) to ensure that the type is
Serializable
. For example,
String
s are
Seri-
alizable
. By default, arrays
are
serializable; however, in a reference-type array, the refer-
enced objects might
not
be. Class
Account
contains
private
data members
account
,
firstName
,
lastName
and
balance
—all of which are
Serializable
. This class also pro-
vides
public
get
and
set
methods for accessing the
private
fields.
Writing Serialized Objects to a Sequential-Access File
Now let's discuss the code that creates the sequential-access file (Fig. 15.10). We concen-
trate only on new concepts here. To open the file, line 27 calls
Files
static
method
newOutputStream
, which receives a
Path
specifying the file to open and, if the file exists,
returns an
OutputStream
that can be used to write to the file. Existing files that are opened
for output in this manner are
truncated
. There is no standard filename extension for files
that store serialized objects, so we chose the
.ser
.
1
// Fig. 15.10: CreateSequentialFile.java
2
// Writing objects sequentially to a file with class ObjectOutputStream.
3
import
java.io.IOException;
4
5
import
java.io.ObjectOutputStream;
import
java.nio.file.Files;
6
import
java.nio.file.Paths;
7
import
java.util.NoSuchElementException;
8
import
java.util.Scanner;
9
10
public class
CreateSequentialFile
11
{
12
private static
ObjectOutputStream output;
// outputs data to file
13
Fig. 15.10
|
Sequential file created using
ObjectOutputStream
. (Part 1 of 3.)