Answer to Question #263005 in Java | JSP | JSF for Tarurendra Kushwah

Question #263005

Write a program to read and write an object to file.

1
Expert's answer
2021-11-08T17:31:51-0500
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;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS