ในทางคอมพิวเตอร์นั้นเราสามารถที่เขียน Object ลงไฟล์แล้ว
อ่านกลับมาเป็น Object ได้ไม่ว่าจะ .Net หรือ Java
ลองมาดูตัวอย่างภาษาจาวาเเบบง่ายกันครับ
private void writeCurrentDir(PreviousDirectory prevDir) throws Exception {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
log.debug("Start write object PreviousDirectory to file");
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(prevDir);
out.close();
log.debug("Write object PreviousDirectory to file success!");
} catch (IOException ex) {
log.error(ex);
throw new Exception(ex);
}
}
สำหรับการอ่าน
private PreviousDirectory getPreviousDir() {
FileInputStream fis = null;
ObjectInputStream in = null;
PreviousDirectory prevDir = null;
try {
log.debug("Start read file to object PreviousDirectory");
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
prevDir = (PreviousDirectory) in.readObject();
in.close();
log.debug("Read file to object PreviousDirectory success!");
} catch (IOException ex) {
//ignore
return null;
} catch (ClassNotFoundException ex) {
//ignore
return null;
}
return prevDir;
}
Thursday, February 18, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment