package exceptionhandling; import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** This program serializes an ArrayList of BankAccount2 objects. */ public class SerializeObjects { public static void main(String[] args) throws IOException, ClassNotFoundException { ArrayList accountList = new ArrayList<>(); final int NUM_ITEMS = 3; double balance; String defaultFileName = "/Users/Mayelin/Documents/Teaching/COP3804/Input_Output_Files/BankAccountObjects.ser"; Object deSerializedObj = null; // Get the serialization file name from the program argument list; else use a default value. String serializationFileName; if (args.length > 0) serializationFileName = args[0]; else serializationFileName = defaultFileName; // try to initialize the accountList object with value from the serialization file. try { deSerializedObj = deSerializeObject(serializationFileName); } catch(FileNotFoundException ex) { System.out.println( "No serialization file was found."); } if (deSerializedObj != null && deSerializedObj instanceof ArrayList) accountList = (ArrayList) deSerializedObj; // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Populate the arraylist for (int i = 0; i < NUM_ITEMS; i++) { // Get an account balance. System.out.print("Enter the balance for account " + (i + 1) + ": "); balance = keyboard.nextDouble(); // Add an object to the arraylist. accountList.add(new BankAccount2(balance)); } System.out.println(accountList); serializeObject(accountList, serializationFileName); } public static Object deSerializeObject(String fileName) throws IOException, ClassNotFoundException { // the following line may throw a FileNotFoundException (a subclass of IOException) FileInputStream dataFile = new FileInputStream(fileName); // the following line may throw an IOException ObjectInputStream objectInputStream = new ObjectInputStream(dataFile); // the following line may throw an IOException and/or a ClassNotFoundException Object deSerializedObject = objectInputStream.readObject(); dataFile.close(); objectInputStream.close(); return deSerializedObject; } public static void serializeObject(Object objectToSerialize, String fileName) throws IOException, ClassNotFoundException { // the following line may throw a FileNotFoundException (a subclass of IOException) FileOutputStream outStream = new FileOutputStream(fileName); // the following line may throw an IOException ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream); // the following line may throw an IOException objectOutputFile.writeObject(objectToSerialize); objectOutputFile.close(); outStream.close(); System.out.println("The serialized object was written to the file."); } }