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;
}
}
我在上面的例子中有几个问题.
>何时使用冲洗方法,为什么要使用它?
> close方法在这里得分是多少?
> myObj2 =(John)ois.readObject(); …请纠正我,如果我错了,我正在读取文件对象并存储到另一个对象并转换为文件对象.
>使用Java进行序列化或持久化数据的替代方法有哪些.我不希望数据作为字节流进入文件.