Java Reference
In-Depth Information
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
Display 10.13, except that here we have used the classes ObjectInputStream and
FileInputStream instead of ObjectOutputStream and FileOutputStream .
Opening a Binary File for Reading
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.
Display 10.15
Some Methods in the Class ObjectInputStream (part 1 of 3)
The classes ObjectInputStream and FileInputStream are in the java.io package.
public ObjectInputStream(InputStream streamObject)
There is no constructor that takes a file name as an argument. If you want to create a stream using
a file name, use
new ObjectInputStream( new FileInputStream( File_Name ))
Alternatively, you can use an object of the class File in place of the File_Name , as follows:
new ObjectInputStream( new FileInputStream( File_Object ))
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 .
 
Search WWH ::




Custom Search