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;
}
}
4 Replies
⌛ This post has been reserved for your question.
Hey @Abdullah! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
Can you show the stack trace?
java.io.InvalidClassException: Student; no valid constructor
at java.base/java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:155)
at java.base/java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:689)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2135)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1653)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:495)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:453)
at Student.main(Student.java:39)
so, did you understand any thing ?
Post Closed
This post has been closed by <@1202613777082880013>.