从ObjectInputStream中读取序列化对象

时间:2013-11-13 10:40:26

标签: java object io serializable

第一次尝试从文件中读取对象时,如何读取我编写的文件?

    private static final long serialVersionUID = -4654676943759320425L;
private ArrayList<ArrayList<Object>> world;
private ArrayList<AFood> foods;
private ArrayList<ABlock> blocks;
private ArrayList<ABug> bugs;
private String name = null;
private int lengthX = 0, lengthY = 0;

这是对象类(只是变量)

open = new FileInputStream(worldSavedAs);
openBuffer = new BufferedInputStream(open);
openIn = new ObjectInputStream(openBuffer);
this.world = openIn.readObject();

这就是我试图读取当前对象的方式

save = new FileOutputStream(worldNameAs + ".aBugsWorld");
saveBuffer = new BufferedOutputStream(save);
saveOut = new ObjectOutputStream(saveBuffer);
saveOut.writeObject(this.worldSave); // Here was the problem

这是我写文件的方式

显然这是不正确的,我不知道如何读取对象,我是否必须逐个插入变量或者作为一个我不知道的整个类。

编辑:我正在将流写入文件而不是导致问题的对象(因为文件IO流无法转换为AWorld)

2 个答案:

答案 0 :(得分:2)

看起来很正确。 但是有人认为,要写在文件上的类必须是可序列化的。

你也可以这样做:

1&GT;要写入档案的类:

 class StudentRecord implements Serializable{
        String name;
        public StudentRecord(String name) {
            this.name=name;
        }  
    }

2&GT;写入文件

            File f=new File("xyz.txt");
            f.createNewFile();
            fo = new FileOutputStream(f);
            ObjectOutput oo=new ObjectOutputStream(fo);
            StudentRecord w=new StudentRecord("MyName");
            oo.writeObject(w);

3&GT;从文件中读取

        File f=new File("xyz.txt");
        fi = new FileInputStream(f);
        ObjectInputStream oi=new ObjectInputStream(fi);
        StudentRecord sr=(StudentRecord)oi.readObject();

答案 1 :(得分:1)

似乎没问题。只需确保您编写/读取Serializable对象,这些对象在您的示例中并不清楚。另外,我会使流构造更简单

ObjectOutputStream out = new ObjectOutputStream(
    new BufferedOutputStream(new FileOutputStrea(file))
);

您无需保存对中间流的引用。

相关问题