This in Java as well. I can't seem to get this method to work, the saving part works great and saves the object. But once I try to read the file it doesn't work and I get ObjectInputStream
errors. I'm new to using the Serializable
interface and none of the other questions seem to help me. The expected output is name Joe, weight 153, height 69
. The errors are:
java.io.InvalidClassException: Person; local class incompatible: stream classdesc serialVersionUID = -1404541419531259795, local class serialVersionUID = 3020781085877336930 at java.io.ObjectStreamClass.initNonProxy(Unknown Source) at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) at java.io.ObjectInputStream.readClassDesc(Unknown Source) at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source)
public static boolean save(Person p, String filename) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(filename));
os.writeObject(p);
os.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Person read(String filename) {
try {
ObjectInputStream oi = new ObjectInputStream(new FileInputStream(
filename));
Object o = oi.readObject();
oi.close();
if (o instanceof Person)
return (Person) o;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Do you want to save or load?");
String option = s.next();
Person p = new Person("Joe", 154, 69);
if (option.equals("save")) {
if (save(p, "newfile")) {
System.out.println("Saved.");
}
}
if (option.equals("load")) {
Person p1 = read("newfile");
if ((p1 != null)) {
System.out.println(p1.getInfo());
}
}
}
}