我正在尝试从文件中加载对象。我首先通过将对象保存到文件来创建文件。如果我仅将一个对象保存到文件中,则可以通过将对象转换为变量而不是arraylist的方式来加载它。但是,如果我尝试将多个对象转换为arraylist,则会不断出现错误。我有时会得到这个:


  animalkingdom.AnimalBuild;本地类不兼容:流classdesc
  serialVersionUID = 8814442576780984798,本地类serialVersionUID =
  -7073710162342893881


或这个


  线程“主”中的异常java.lang.ClassCastException:
  无法将animalkingdom.AnimalBuild强制转换为java.util.ArrayList
  animalkingdom.AnimalKingdom.readFile(AnimalKingdom.java:146)在
  animalkingdom.AnimalKingdom.main(AnimalKingdom.java:123)Java结果:
  1个


写功能

  // 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);
        }
    }


读取功能

  // 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);
    }
}


动物的身材

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";
}
}

最佳答案

序列化数据时,需要以与写入方式兼容的方式读取数据。您正在单独编写每个元素,因此要阅读此内容,您需要单独阅读它们。

但是,编写列表更为简单。

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("animal2.txt"))) {
    oos.writeObject(a);
}


阅读清单

List<AnimalBuild> animalList;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("animal2.txt"))) {
     animalList = (List<AnimalBuild>) ois.readObject(); // casting object
}

07-24 09:21