【发布时间】:2011-11-10 04:04:15
【问题描述】:
import java.io. * ;
public class Ser {
public static void main(String args[]) {
try {
John myObj = new John("Sachin", "Cricket");
System.out.println(myObj);
FileOutputStream fos = new FileOutputStream("FileName");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myObj);
oos.flush();
oos.close();
} catch (Exception e) {
System.out.println("Expection" + e);
System.exit(0);
}
try {
John myObj2;
FileInputStream fis = new FileInputStream("FileName");
ObjectInputStream ois = new ObjectInputStream(fis);
myObj2 = (John) ois.readObject();
ois.close();
System.out.println("New Object" + myObj2);
} catch (Exception e) {
System.out.println("Expection" + e);
System.exit(0);
}
}
}
class John implements Serializable {
private String name;
private String department;
public John(String name, String department) {
this.name = name;
this.department = department;
}
public String toString() {
return "Name" + name + " " + "Department" + department;
}
}
在上面的例子中我有几个问题。
- 什么时候使用flush方法,为什么要使用它?
- close 方法在这里携带分数是什么?
-
myObj2 = (John) ois.readObject();...如果我错了,请纠正我,我正在读取文件对象并存储到另一个对象中并对文件对象进行类型转换。 - 在 Java 中序列化或持久化数据的替代方法是什么。我不希望数据作为字节流进入文件。
【问题讨论】:
-
@John Cooper:我用它来解决 BufferedImage 的泄漏(即使没有对它的引用,也不会收集未刷新的图像)。哦,等等... 那个 flush ; )
-
你所说的“携带乐谱”是什么意思?
标签: java serialization