-->

(Meta Program) Serialization And Deserialization using files (Alternative) in Java

1 minute read

This Java code defines a class called "Serial" that has several methods to save and read data from files. The data being saved and read is stored in ArrayList objects.


The savedata() method takes in two parameters: an integer i and an ArrayList data. Based on the value of i, the method assigns a string variable "a" a different value: "fnames", "lnames", "pnames", or "phnos". It then creates a FileOutputStream object and an ObjectOutputStream object, and writes the ArrayList data to a file with the name of filename.ser".


The readdata() method takes an integer i as a parameter and assigns a string variable "a" a value based on the value of i. It then creates an ArrayList b and initializes it with an empty ArrayList. It then creates an FileInputStream and an ObjectInputStream object and reads the data from the file with the name a.ser" and assigns it to ArrayList b . Finally, it returns b.


In the main method, the program creates several ArrayList objects to store first names, last names, parent names, and phone numbers. It then uses a while loop to repeatedly prompt the user for input and add the input to the appropriate ArrayList. After each set of inputs, the program calls the savedata() method to save the data to a file. Once the loop exits, the program calls the readdata() method to read the data from the files and prints it out.

Tap on the link to open the code.