3.2.5.2 Binary Output3.2.5.1 Object Serialization3.2.5 Binary Input and Output3.2.5.3 Binary Input

3.2.5.2 Binary Output

For writing binary data, we have to create an output byte stream of type FileOutputStream:

 
   public class FileOutputStream extends OutputStream
   {
     public FileOutputStream(String name) 
       throws FileNotFoundException;
     public void write(byte[] b, int off, int len) 
       throws IOException;
     public void close() throws IOException;
     ...
   }

 

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

  String fileName = "tuple.dat";
  OutputStream fstream = new FileOutputStream(fileName);

Rather than writing directly to this stream, we insert a buffered byte stream of type BufferedOutputStream:  

   public class BufferedOutputStream extends FilterOutputStream
   {
     public BufferedOutputStream(OutputStream out);
     public void write(byte[] b, int off, int len) 
       throws IOException;
     public void flush() throws IOException;
     public void close() throws IOException;
     ...
   }

 

We can thus connect a buffered byte stream to the stream fstream created above:

   OutputStream bstream = new BufferedOutputStream(bstream);

The write method of BufferedOutputStream allows to write a byte array segment b[off...off+len-1] to a file. This may be sufficient for various applications that write binary data (such as images); for the purpose of writing objects we need however a more convenient interface. Such an interface is provided by class ObjectOutputStream:  

   public class ObjectOutputStream extends OutputStream ...
   {
     public ObjectOutputStream(OutputStream out) 
       throws IOException;
     public final void writeObject(Object object) 
       throws IOException;
     public void flush() throws IOException;
     public void close() throws IOException;
     ...
   }

We may thus connect an object byte stream to the stream bstream created above:

   ObjectOutputStream out = new ObjectOutputStream(bstream);

Our object tuple can now be written as

   out.writeObject(tuple);

When the file is closed, the object is persistent on the disk file:

   out.close();

Now we need a possibility to reverse the process, i.e., to read an object from file into memory.


© Wolfgang Schreiner; February 3, 2005

3.2.5.2 Binary Output3.2.5.1 Object Serialization3.2.5 Binary Input and Output3.2.5.3 Binary Input