3.2.5.4 Putting all Together3.2.5.3 Binary Input3.2.5 Binary Input and Output3.2.6 File Management

3.2.5.4 Putting all Together

We can summarize the content of binary file I/O by the following methods for reading and writing a Tuple object.

   // returns true iff tuple could be successfully written to fileName
   static boolean writeTuple(String fileName, Tuple tuple)
   {
     ObjectOutputStream out = null;
     try
     {
       OutputStream fstream = new FileOutputStream(fileName);
       OutputStream bstream = new BufferedOutputStream(fstream);
       out = new ObjectOutputStream(bstream);
       out.writeObject(tuple);
       return true;
     }
     catch(Exception e)
     {
       System.out.println("Error: " + e);
       return false;
     }
     finally
     {
       try
       {
         if (out != null) out.close();
       }
       catch(IOException e)
       { 
         System.out.println("Error: " + e);
         return false;
       }
     }
   }

We catch in this method all kinds of exceptions by a single handler and we attempt to close the out stream in any case. Please note that if the closing of out fails, false is returned (even if the protected code block is exited by return true).

   Tuple readTuple(String fileName)
   {
     ObjectInputStream in = null;
     try
     {
       InputStream fstream = new FileInputStream(fileName);
       InputStream bstream = new BufferedInputStream(fstream);
       in = new ObjectInputStream(bstream);
       return (Tuple)in.readObject();
     }
     catch(Exception e)
     {
       System.out.println("Error: " + e);
     }
     finally
     {
       try
       {
         if (in != null) in.close();
       }
       catch(IOException e)
       { }
     }
     return null;
   }


© Wolfgang Schreiner; February 3, 2005

3.2.5.4 Putting all Together3.2.5.3 Binary Input3.2.5 Binary Input and Output3.2.6 File Management