我想这将是一个非常基本的问题,但我一直在寻找答案几个小时,但我无法弄清楚我的代码哪里出错了。所以:我确实序列化了一个名为 SerializableObject 的对象,而不是读回它。在反序列化方法中,我得到一个临时对象,我想将其复制到另一个 new SerializeableObject
,之后我想使用它,但我无法正确复制它,但是临时对象在反序列化时正确获取了值。这是我的课程: SeralizeableObject:
public class SerializableObject implements Serializable, Cloneable{
private Vector<int[]> mixMade;
private Vector<int[]> stepsMade;
private long time;
private int steps;
private int winnerState;
public SerializableObject(Vector<int[]> mixMade, Vector<int[]> stepsMade,
long time, int steps, int winnerState) {
this.mixMade = mixMade;
this.stepsMade = stepsMade;
this.time = time;
this.steps = steps;
this.winnerState = winnerState;
}
@Override
public String toString() {
String str = "";
for(int[] mixEl : mixMade){
str += mixEl[0] + ", " + mixEl[1] + "|";
}
str += " mixes\n";
for(int[] stepEl : stepsMade){
str += stepEl[0] + ", " + stepEl[1] + "|";
}
str += " steps\n";
str += "time: " + time + ", stepsnum: " + steps + ",
winstate: " + winnerState;
return str;
}
@Override
public SerializableObject clone() {
SerializableObject serObj;
Vector<int[]> mixMadeTemp = new Vector<int[]>();
Vector<int[]> stepsMadeTemp = new Vector<int[]>();
for(int i = 0; i < mixMade.size(); ++i){
mixMadeTemp.add(mixMade.get(i));
}
for(int i = 0; i < stepsMade.size(); ++i){
stepsMadeTemp.add(stepsMade.get(i));
}
serObj = new SerializableObject(mixMadeTemp, stepsMadeTemp,
time, steps, winnerstate);
return serObj;
}
}
序列化器:
public class ObjectSerializator {
public ObjectSerializator() {
}
public void toFile(String filepath, SerializableObject serObj){
ObjectOutputStream out;
try{
FileOutputStream fileOut = new FileOutputStream(filepath);
out = new ObjectOutputStream(fileOut);
out.writeObject(serObj);
}catch (IOException ex) {
}
}
public void fromFile(String filepath, SerializableObject serObj){
SerializableObject tempSerObj;
try {
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream in = new ObjectInputStream(fileIn);
tempSerObj = (SerializableObject) in.readObject();
System.out.println(tempSerObj + "TEMP");
serObj = tempSerObj.clone();
in.close();
fileIn.close();
} catch (IOException ex) {
} catch (ClassNotFoundException ex) {
}
}
}
注意: serobj 引用正确地指向了良好的值,在 fromFile 方法 A filechooser 类中,用户可以从中选择要加载的文件:
public class FileChooser extends JFileChooser{
private ObjectSerializator serializator;
public FileChooser() {
serializator = new ObjectSerializator();
}
public void load(SerializableObject serObj){
int retValue = showOpenDialog(null);
serializator.fromFile(getSelectedFile().getAbsolutePath(), serObj);
}}
比在我的大型机中,我从按钮操作中调用它
public void load(){
SerializableObject serObj = new SerializableObject(new Vector<int[]>(), new
Vector<int[]>(), 10, 10, 200);
fileChooser.load(serObj);
System.out.println(serObj + " LAST");
}
这是我的输出:
3, 2|4, 3| mixes
0, 0|0, 1|0, 0| steps
time: 6000, stepsnum: 3, winstate: 0TEMP
-------------------
mixes
steps
time: 10, stepsnum: 10, winstate: 200 LAST