So I was trying to serialize an arraylist of object that hold names but it gives me unserializable error although implemented it in both classes too after it failed to run when i implemented it the main class only.
I will paste the code and the error message
main class
secondary classpackage serial; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Scanner; public class main implements Serializable { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); ArrayList<names> name= new ArrayList<names>(); { name.add(new names()); File File = new File("C:\\Users\\kuchuk borom debbarm\\Desktop\\test\\name.txt"); if(File.exists()) { } else { File.createNewFile(); } ObjectOutputStream fileF= new ObjectOutputStream(new FileOutputStream(File)); fileF.writeObject(name); //this is where the code fails fileF.close(); } } }
here is the errorpackage serial; import java.io.Serializable; import java.util.Scanner; public class names implements Serializable { Scanner input=new Scanner(System.in); public names() { System.out.println("uy"); String names=input.nextLine(); } }
uy kuku Exception in thread "main" java.io.NotSerializableException: java.util.Scanner at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185) at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553) at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510) at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349) at java.base/java.util.ArrayList.writeObject(ArrayList.java:896) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at java.base/java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1130) at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1497) at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433) at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179) at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349) at serial.main.main(main.java:35)