3.2.5.3 Binary Input3.2.5.2 Binary Output3.2.5 Binary Input and Output3.2.5.4 Putting all Together

3.2.5.3 Binary Input

For reading binary data, we have to create an input byte stream of type FileInputStream:

   public FileInputStream extends InputStream
   {
     public FileInputStream(String fileName) 
       throws FileNotFoundException;
     public int read(byte[] b, int off, int len) 
       throws IOException;
     public void close() throws IOException;
     ...
   }

 

We can thus create a byte input stream connected to file "tuple.dat" as:

  String fileName = "tuple.dat";
  InputStream fstream = new FileInputStream(fileName);

For getting better efficiency, we may want to connect this stream to a buffered input stream of type BufferedInputStream:  

   public BufferedInputStream extends FilterInputStream
   {
     public BufferedInputStream(InputStream in);
     public int read(byte[] b, int off, int len) 
       throws IOException;
     public void close() throws IOException;
     ...
   }

We can thus create a buffered input stream connected to fstream as follows:

  InputStream bstream = new BufferedInputStream(fstream);

The read method of BufferedInputStream allows to read a byte array segment b[off...off+len-1] from a file. The function returns the number of bytes actually read or -1, if the end of file has occurred. This interface may be already sufficient for various applications that read binary data (such as images). For the purpose of reading objects from a binary stream we need the interface of class ObjectInputStream:  

   public class ObjectInputStream extends InputStream implements ...
   {
     public ObjectInputStream(InputStream in) 
       throws IOException;
     public final Object readObject() throws IOException, 
       OptionalDataException, ClassNotFoundException;
     public void close() throws IOException;
     ...
   }

We may thus connect an object input stream to the stream bstream as follows:

   ObjectInputStream in = new ObjectInputStream(bstream);

The tuple object may be restored as:

   Tuple tuple = (Tuple)in.readObject();

The readObject method raises a OptionalDataException when the stream contains unexpected data rather than an object description; the method raises a ClassNotFoundException when the class of the object read is unknown to the program.


© Wolfgang Schreiner; February 3, 2005

3.2.5.3 Binary Input3.2.5.2 Binary Output3.2.5 Binary Input and Output3.2.5.4 Putting all Together