第一次尝试从文件中读取对象,我将如何读取我编写的文件?
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)
最佳答案
看起来是正确的。 但有人认为,要写入文件的类必须是可序列化的。
你也可以这样做:
1.> 要写入文件的类:
class StudentRecord implements Serializable{
String name;
public StudentRecord(String name) {
this.name=name;
}
}
2.> 写入文件
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.> 从文件中读取
File f=new File("xyz.txt");
fi = new FileInputStream(f);
ObjectInputStream oi=new ObjectInputStream(fi);
StudentRecord sr=(StudentRecord)oi.readObject();
关于java - 从 ObjectInputStream 读取序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19951550/