简体   繁体   English

反序列化具有多个对象的 ArrayList

[英]Deserializing an ArrayList with multiple objects

I have stored multiple objects in Teacher ArrayList and I'm trying to deserialize it, but it shows the garbage value.我在 Teacher ArrayList存储了多个对象,我正在尝试对其进行反序列化,但它显示了垃圾值。

public void Write(){
    try{
        FileOutputStream fs=new FileOutputStream("S.txt");
        ObjectOutputStream os=new ObjectOutputStream(fs);
        os.writeObject(teachers);

        os.close();
    }catch(Exception e)
    {System.out.println(e);}

}


public void Read(){
    try
    {
        FileInputStream fis = new FileInputStream("E:\\Books\\OOP\\Teacher\\S.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        teachers = (ArrayList<Teacher>) ois.readObject();
        for(Teacher i: teachers){
            System.out.println(i.toString());
        }
        ois.close();
        fis.close();
    }catch(IOException ioe){
        System.out.println("Error");
        return;
    }catch(ClassNotFoundException c){
        System.out.println("Class not found");

        return;
    }
}

You are using object streams, which persist your serialized objects in binary, regardless of the extension of the file (which happens to be ".txt" here, ambiguously suggesting that it'll be a text file when written).您正在使用对象流,它以二进制形式保存序列化对象,而不管文件的扩展名(这里恰好是“.txt”,含糊不清地暗示它在写入时将是一个文本文件)。

You cannot view anything human-like from your file with a text editor when the data written is binary data.当写入的数据是二进制数据时,您无法使用文本编辑器从文件中查看任何类似人类的内容。

If your "garbage values" also get printed when you iterate your List<Teacher> upon de-serialization, it implies that:如果在反序列化时迭代List<Teacher>时也打印了“垃圾值”,则意味着:

  1. (De-)serialization actually succeeded (ie you've written your List<Teacher> to file and retrieved it) (反)序列化实际上成功了(即您已将List<Teacher>写入文件并检索它)
  2. Your Teacher class might not override toString properly or at all, so it prints the Type@hashCode notation from Object#toString when fed to the system output print stream您的Teacher类可能无法正确覆盖或根本没有覆盖toString ,因此当馈送到系统输出打印流时,它会从Object#toString打印Type@hashCode符号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM