Java File I/O with Serialization Guide
Q: Create a Java program that reads and writes data to a file, including features such as serialization, deserialization, and exception handling.
- Java
- Mid level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
Sure, here is an example Java program that reads and writes data to a file using serialization and deserialization. The program creates a class called Person and writes a list of Person objects to a file using serialization. It then reads the data back from the file and prints it to the console using deserialization.
import java.io.*; import java.util.ArrayList; import java.util.List; public class FileSerializationExample { public static void main(String[] args) { String fileName = "persons.ser"; // create a list of Person objects List<Person> persons = new ArrayList<>(); persons.add(new Person("John", 30)); persons.add(new Person("Jane", 25)); persons.add(new Person("Bob", 40)); // serialize the list of persons to a file try { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(persons); oos.close(); fos.close(); System.out.println("Persons written to file successfully."); } catch (IOException e) { e.printStackTrace(); } // read the list of persons back from the file and print to console try { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); List<Person> readPersons = (List<Person>) ois.readObject(); ois.close(); fis.close(); System.out.println("Persons read from file:"); for (Person p : readPersons) { System.out.println(p); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } // Person class with name and age properties static class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } }
In this example, the Person class has two properties: name and age. The program creates a list of Person objects and writes it to a file using serialization. The ObjectOutputStream class is used to write the objects to the file. The program then reads the list of Person objects back from the file using deserialization, and prints it to the console. The ObjectInputStream class is used to read the objects from the file.
Note that the Person class implements the Serializable interface. This allows the objects to be serialized and deserialized. If a class does not implement the Serializable interface, a NotSerializableException will be thrown at runtime when trying to serialize or deserialize an object of that class.


