Java - Serialization - Using Serializable read and write object data to file
Java - Serialization - Using Serializable read and write object data to file
CODE
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
try{
Student s1 = new Student("Pedro", 30);
String fileName = "student.txt";
//write the object to the file
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(fileName));
output.writeObject(s1);
output.flush();
output.close();
//read the data from the file and assign it to the object
ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileName));
Student s2 = (Student)input.readObject();
input.close();
//display the details
System.out.println(s2.toString());
}
catch(Exception e) {
System.out.println(e);
}
}
}
class Student implements Serializable {
public String Name;
public int Age;
public Student(String name, int age) {
this.Name = name;
this.Age = age;
}
@Override
public String toString() {
String result = "Name: " + Name + "\n";
result += "Age: " + Age;
return result;
}
}
Comments
Post a Comment