+ 1

How to read Arraylist to a file and read it?

i have some Class : Student, Teacher, Main and SaveRead in finally i want save and read an array list like this [Teacher1 [Student1, 101], [Student2, 101], Teacher2 [Student1, 101], [Student2, 101]] to a file with code below. but has some Errors. public class SaveRead implements Serializable { Scanner vorodi = new Scanner(System.in); private static final String PATH = "D:/teachers.txt"; public void saveFile(ArrayList<Teacher> teachers) throws IOException { try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH))) { os.writeObject(teachers); } } public ArrayList<Teacher> readFile() throws ClassNotFoundException, IOException { try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH))) { return (ArrayList<Teacher>) is.readObject(); } } } and Error: Exception in thread "main" java.io.NotSerializableException: university.Teacher 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:498) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1028) 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 university.SaveRead.saveFile(SaveRead.java:23) at university.SchoolManager.main(SchoolManager.java:27) Java Result: 1

20th May 2017, 10:43 AM
hamid
hamid - avatar
1 Resposta
0
Is Teacher class serializable?
30th May 2017, 4:05 PM
Twelfty
Twelfty - avatar