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中序列化或持久化数据的替代方案有哪些?我不希望数据以字节流形式存储到文件中。