Java Reference
In-Depth Information
17.26
If you serialize two objects of the same type, will they take the same amount of
space? If not, give an example.
17.27
Is it true that any instance of
java.io.Serializable
can be successfully serial-
ized? Are the static variables in an object serialized? How do you mark an instance
variable not to be serialized?
17.28
Can you write an array to an
ObjectOutputStream
?
17.29
Is it true that
DataInputStream
/
DataOutputStream
can always be replaced by
ObjectInputStream
/
ObjectOutputStream
?
17.30
What will happen when you attempt to run the following code?
import
java.io.*;
public class
Test {
public static void
main(String[] args)
throws
IOException {
try
( ObjectOutputStream output =
new
ObjectOutputStream(
new
FileOutputStream(
"object.dat"
)); ) {
output.writeObject(
new
A());
}
}
}
class
A
implements
Serializable {
B b =
new
B();
}
class
B {
}
Java provides the
RandomAccessFile
class to allow data to be read from and
written to at any locations in the file.
Key
Point
All of the streams you have used so far are known as
read-only
or
write-only
streams. These
streams are called
sequential streams
. A file that is opened using a sequential stream is called
a
sequential-access file
. The contents of a sequential-access file cannot be updated. However,
it is often necessary to modify files. Java provides the
RandomAccessFile
class to allow
data to be read from and written to at any locations in a file. A file that is opened using the
RandomAccessFile
class is known as a
random-access file
.
The
RandomAccessFile
class implements the
DataInput
and
DataOutput
interfaces,
as shown in Figure 17.18. The
DataInput
interface (see Figure 17.9) defines the methods
for reading primitive-type values and strings (e.g.,
readInt
,
readDouble
,
readChar
,
readBoolean
,
readUTF
) and the
DataOutput
interface (see Figure 17.10) defines the
methods for writing primitive-type values and strings (e.g.,
writeInt
,
writeDouble
,
writeChar
,
writeBoolean
,
writeUTF
).
When creating a
RandomAccessFile
, you can specify one of two modes:
r
or
rw
. Mode
r
means that the stream is read-only, and mode
rw
indicates that the stream allows both read
and write. For example, the following statement creates a new stream,
raf
, that allows the
program to read from and write to the file
test.dat
:
read-only
write-only
sequential-access file
random-access file
RandomAccessFile raf =
new
RandomAccessFile(
"test.dat"
,
"rw"
);
If
test.dat
already exists,
raf
is created to access it; if
test.dat
does not exist, a new file named
test.dat
is created, and
raf
is created to access the new file. The method
raf.length()
returns the number of bytes in
test.dat
at any given time. If you append new data into the file,
raf.length()
increases.
Search WWH ::
Custom Search