Java Reference
In-Depth Information
19.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
19.26
If you serialize two objects of the same type, will they take the same amount of
space? If not, give an example.
19.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?
19.28
Can you write an array to an ObjectOutputStream ?
19.29
Is it true that DataInputStream / DataOutputStream can always be replaced by
ObjectInputStream / ObjectOutputStream ?
19.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 {
ObjectOutputStream output =
new ObjectOutputStream( new FileOutputStream( "object.dat" ));
output.writeObject( new A());
}
}
class A implements Serializable {
B b = new B();
}
class B {
}
19.7 Random-Access Files
Java provides the RandomAccessFile class to allow a file to be read from and
written to at random locations.
Key
Point
read-only
write-only
sequential
random-access file
All of the streams you have used so far are known as read-only or write-only streams. The exter-
nal files of these streams are sequential files that cannot be updated without creating a new file.
However, it is often necessary to modify files. Java provides the RandomAccessFile class to
allow a file to be read from and written to at random locations.
The RandomAccessFile class implements the DataInput and DataOutput interfaces,
as shown in Figure 19.17. The DataInput interface (see Figure 19.9) defines the methods for
reading primitive type values and strings (e.g., readInt , readDouble , readChar ,
readBoolean , readUTF ), and the DataOutput interface (see Figure 19.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 :
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