Java Reference
In-Depth Information
Display 10.15 Some Methods in the Class ObjectInputStream (part 3 of 3)
public int skipBytes( int n) throws IOException
Skips n bytes.
public void close() throws IOException
Closes the stream's connection to a file.
The input stream for reading from the binary file numbers.dat is opened as follows:
ObjectInputStream inputStream =
new ObjectInputStream( new FileInputStream("numbers.dat"));
Note that this is identical to how we opened a file using ObjectOutputStream in Dis-
play 10.13, except that here we've used the classes ObjectInputStream and FileIn-
putStream instead of ObjectOutputStream and FileOutputStream .
Opening a Binary File for Reading
You create a stream of the class ObjectInputStream and connect it to a binary file as
follows:
SYNTAX
ObjectInputStream Input_Stream_Name =
new ObjectInputStream( new FileInputStream( File_Name ));
The constructor for FileInputStream may throw a FileNotFoundException , which is a
kind of IOException . If the FileInputStream constructor succeeds, then the constructor
for ObjectInputStream may throw a different IOException .
EXAMPLES
ObjectInputStream inputFile =
new ObjectInputStream( new FileInputStream("somefile.dat"));
After this, you can use the methods in Display 10.15 to read from the file.
ObjectInputStream allows you to read input values of different types from the same
file. So, you may read a combination of, for example, int values, double values, and
String values. However, if the next data item in the file is not of the type expected by the
reading method, the result is likely to be a mess. For example, if your program writes an
integer using writeInt , then any program that reads that integer should read it using
readInt . If you instead use readLong or readDouble , your program will misbehave.
Note that, as illustrated in Display 10.16, you close a binary input stream in the
same way that you close all the other I/O streams we have seen.
reading
multiple
types
closing a
binary file
 
Search WWH ::




Custom Search