serialization in java

//the code display error when i can "readObject" method.
public class Person {

private String city;


public Person(String city) {
this.city = city;
}


public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}
import java.io.*;

public class Student extends Person implements Serializable {
private int age;
private String name;

public Student( String name, String city,int age) {
super(city);
this.age = age;
this.name = name;
}
@Serial
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeUTF(this.getCity());
}
@Serial
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
this.setCity(ois.readUTF());

}

public static void main(String[] args) {
Student student= new Student("Boudaoud","mascara",20);
try(FileOutputStream fos= new FileOutputStream("src/resources/test.ser");
ObjectOutputStream oos= new ObjectOutputStream(fos))
{
oos.writeObject(student);
System.out.println("Success");

}catch (IOException ioe){
ioe.printStackTrace();
return;
}

try(FileInputStream fis= new FileInputStream("src/resources/test.ser");
ObjectInputStream ois=new ObjectInputStream(fis)) {
Student s=(Student) (ois.readObject());
System.out.println("You wrote the student "+s.getName()+" his age :"+s.getAge()+" live in"+s.getCity());
}catch (ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
}
public int getAge() {
return age;
}

public String getName() {
return name;
}
}
Was this page helpful?