In trying to learn about Serializable I found this example online: https://samderlust.com/dev-blog/java/write-read-arraylist-object-file-java but am unable to get it to run without error. Similar efforts with other examples as well as my own project have failed. Can anyone get this demo to run without error in our IDE? Thanks.
import java.io.*;
import java.util.ArrayList;
class Person implements Serializable {
String firstName;
String lastName;
int birthYear;
Person(String firstName, String lastName, int birthYear) {
this.firstName = firstName;
this.lastName = lastName;
this.birthYear = birthYear;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", birthYear=" + birthYear +
"}\n";
}
}
void setup() {
Person p1 = new Person("Jony", "Deep", 1980);
Person p2 = new Person("Andrew", "Justin", 1990);
Person p3 = new Person("Valak", "Susan", 1995);
ArrayList<Person> people = new ArrayList<>();
people.add(p1);
people.add(p2);
people.add(p3);
//write to file - change filePath for your system
try {
FileOutputStream writeData = new FileOutputStream("/Users/xxxx/peopledata.ser");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(people);
writeStream.flush();
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
// Change filePath to match one above
try {
FileInputStream readData = new FileInputStream("/Users/xxxx/peopledata.ser");
ObjectInputStream readStream = new ObjectInputStream(readData);
ArrayList people2 = (ArrayList<Person>) readStream.readObject();
readStream.close();
println(people2.toString());
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}