Write a program to read and write an object to file.
import java.io.*;
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee("Joseph", 56, "Male");
Employee e2 = new Employee("Anne", 49, "Female");
try {
FileOutputStream file_out = new FileOutputStream(new File("objectfile.txt"));
ObjectOutputStream obj = new ObjectOutputStream(file_out);
obj.writeObject(e1);
obj.writeObject(e2);
obj.close();
file_out.close();
FileInputStream file_in = new FileInputStream(new File("objectfile.txt"));
ObjectInputStream obj2 = new ObjectInputStream(file_in);
Employee pr1 = (Employee) obj2.readObject();
Employee pr2 = (Employee) obj2.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
obj2.close();
file_in.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String gender;
Employee() {
};
Employee(String n, int a, String g) {
name = n;
age = a;
gender = g;
}
@Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}
Comments
Leave a comment