aCiotola / ReservationSys

Software Dev 3 - Assignment
0 stars 0 forks source link

Part V – Object Serialization –Utility class - code provided #19

Closed aCiotola closed 7 years ago

aCiotola commented 7 years ago

Note: this part is also done in Lab 10:

The serializeObject and deserializeObject utility methods can be used to serialize any type of object; if you haven’t done so already, create a class called Utilities in your groupX.util package in your CommonX project.

In order to prevent the Utilities class from being instantiated, code a private do-nothing constructor in the class.

Add the following import statements to the Utility class’s compilation unit.

import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;

Code the serializeObject method.

Code the following serializeObject method in your Utilities class.

public static void serializeObject  (Object object, 
    String fileSpecification) throws IOException   {
    ObjectOutputStream out = null;
    try     {
        out = new ObjectOutputStream (
            new FileOutputStream (fileSpecification));

        out.writeObject (object);

    }
    catch (IOException e){
        //normally the exception would be logged to file then thrown
        throw new IOException ("Error serializing object to \n" +
            fileSpecification  + " " + e);
    }
    finally     {
        if (out != null)
            out.close ();
    }
}

Code the deserializeObject method.

Code the following deserializeObject method in your Utilities class.

public static Object deserializeObject (String fileSpecification)
    throws IOException, ClassNotFoundException {

    ObjectInputStream in = null;
    try {
        Object obj = null;
        in = new ObjectInputStream
        (new FileInputStream (fileSpecification));
        if (in != null)
            obj = in.readObject ();

        return obj;
    }
    catch (ClassNotFoundException | IOException e)
    {
        //normally the exception would be logged to file then thrown
        throw new IOException ("Error deserializing object from " +
           fileSpecification + "\n" + e);
    }
    finally
    {
        if (in != null)
            in.close ();
    }
}
aCiotola commented 7 years ago

Code added