Java Reference
In-Depth Information
you read an object back from a stream, you can still serialize your objects by declaring the non-serializable
fields as
transient
.
Transient Data Members of a Class
If your class has fields that are not serializable, or that you just don't want to have written to the stream, you
can declare them as
transient
. For example:
public class MyClass implements Serializable {
private static final long serialVersionUID = 8001L;
transient protected Graphics g; // Transient class member
// Rest of the class definition
}
Declaring a data member as
transient
prevents the
writeObject()
method from attempting to write
the data member to the stream. When the class object is read back, the object is created properly, including
any members that you declared as
transient
. The transient class members just won't have their values set,
because they were not written to the stream. Unless you arrange for something to be done about it, the tran-
sient fields are
null
.
You may well want to declare some data members of a class as
transient
. You would do this when they
have a value that is not meaningful long term or out of context — objects that represent the current time,
or today's date, for example. You must either provide code to explicitly reconstruct the members that you
declare as
transient
when the object that contains them is read from the stream or accept the defaults for
these that apply when the objects are re-created.
READING AN OBJECT FROM A FILE
Reading objects back from a file is just as easy as writing them. First, you need to create an
ObjectIn-
putStream
object for the file. To do this you just pass a reference to an
InputStream
object that encapsu-
lates the file to the
ObjectInputStream
class constructor:
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java Stuff").resolve("JunkObjects.bin");
// Verify that the file exists...
try (ObjectInputStream objectIn =
new ObjectInputStream(new BufferedInputStream(
Files.newInputStream(file)))){
// Read objects from the file...
} catch(IOException e) {
e.printStackTrace();
}
The
ObjectInputStream
constructor throws an exception of type
StreamCorruptedException
— a
subclass of
IOException
— if the stream header is not correct, or of type
IOException
if an error occurs
while reading the stream header. Calling
newInputStream()
from the
Files
class with the
Path
object,