How to implement Serializable?

How should I implement the Serializable interface?

I have a class Student , and I need to save it to disk. For my homework, I need to serialize five different Student objects and save them in a file.

 class Student { String mFirstName; String mSecondName; String mPhoneNumber; String mAddress; String mCity; Student(final String pFirstName, final String pSecondName, final String pPhoneNumber, final String pAddress, final String pCity){ this.mFirstName = pFirstName; this.mSecondName = pSecondName; this.mPhoneNumber = pPhoneNumber; this.mAddress = pAddress; this.mCity = pCity; }} 

I tried using ObjectOutputStream to serialize Student , but it throws an error:

 ObjectOutputStream lOutputStream = new ObjectOutputStream(new FileOutputStream("file.txt", true)); lOutputStream.write(new Student("foo","bar","555-1234","Flat 40","Liverpool")); 
+7
java serialization
source share
1 answer

The only thing you need to do is implement Serializable. String The only thing to worry about when you implement this interface is to make sure that all instances of this class / object contain only serializable objects. However, String is already being serialized, so you only need to add Serializable tools. http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

 public class Student implements Serializable { String first; String second; String phone; String cityAddress; String cityStreet; public Student(String s1, String s2, String s3, String s4, String s5) { first = s1; second = s2; phone = s3; cityAddress = s4; cityStreet = s5; } } 
+15
source share

All Articles