1
votes

I'm programming a simple Java gmail client to finish my A level project. When the following section of code runs I always get an error. I can't find out why the error is there.

public static void save(List<user> u3){
    try {

        FileOutputStream fos=new FileOutputStream("users.ser");
        ObjectOutputStream oos= new ObjectOutputStream(fos);
        oos.writeObject(u3);

    }catch (Exception e) {
        e.printStackTrace(); //Added due to suggestion of commentor
    }   
}

The error is:

java.io.NotSerializableException: user at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at java.util.ArrayList.writeObject(ArrayList.java:762) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348) at main.saveu(main.java:65) at main.main(main.java:42) at __SHELL12.run(__SHELL12.java:6) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at bluej.runtime.ExecServer$3.run(ExecServer.java:730)

2
Does the user class implement Serializable? - Dakoda
The main class or the user class? neither of them implement serializable - Andrew1024
You should read up on how to serialize objects in Java - Tezra
Thanks so much Tezra im not so familiar with the serializable class and I kinda overlooked some stuff thanks for the link and thanks to everybody else - Andrew1024

2 Answers

2
votes

Your class "User" does not implement Serializable. Serializable is mostly a tagging interface. You do not need to do anything to implement it. Simply declaring that your class implements it is enough.

class User implements Serializable{
    // your existing code here
}
0
votes

As mentioned in the official documentation of JEE7:

Thrown when an instance is required to have a Serializable interface

So you need just to implement the Serializable interface.

class User implements Serializable {
//Staff
}