I'm trying to load an object in from a file. I first create the file by saving an object to it. If I save only one object to a file I can get it loaded in by casting the object into a variable stead of an arraylist. But if I try to cast mulitple objects into an arraylist I keep getting errors. I sometimes will get this:
animalkingdom.AnimalBuild; local class incompatible: stream classdesc serialVersionUID = 8814442576780984798, local class serialVersionUID = -7073710162342893881
or this
Exception in thread "main" java.lang.ClassCastException: animalkingdom.AnimalBuild cannot be cast to java.util.ArrayList at animalkingdom.AnimalKingdom.readFile(AnimalKingdom.java:146) at animalkingdom.AnimalKingdom.main(AnimalKingdom.java:123) Java Result: 1
write function
// function to write object to file
public static void writeToFile(ArrayList<AnimalBuild> a) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream("animal2.txt"));
for (AnimalBuild s : a) { // loop through and write objects to file.
oos.writeObject(s);
}
}
read function
// function to read from file
public static void readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("animal2.txt"));
@SuppressWarnings("unchecked")
ArrayList<AnimalBuild> animalList = (ArrayList<AnimalBuild>)ois.readObject(); // casting object
Iterator it = animalList.iterator();
while(it.hasNext()) {
String obj = (String)it.next();
System.out.println(obj);
}
}
Animal Build
class AnimalBuild implements Serializable {
private static final long serialVersionUID = 8814442576780984798L;
//private static final long serialVersionUID = -12049485535619732L;
public String Animaltype, Species, Color;
public AnimalBuild (String animaltype , String species, String color )
{
this.Animaltype = animaltype;
this.Species = species;
this.Color = color;
}
public String getType() {
return this.Animaltype;
}
public String getSpecies() {
return this.Species;
}
public String getColor() {
return this.Color;
}
public String setType(String newType) {
return (this.Animaltype=newType);
}
public String setSpecies(String newSpecies) {
return (this.Species=newSpecies);
}
public String setColor(String newColor) {
return (this.Color=newColor);
}
public String toString ()
{
return "\n\n Animal Type: " + this.Animaltype + "\n Species: " + this.Species + "\n Color: " + this.Color + "\n";
}
}
ArrayList.