Java圖書管理系統練習程式(三)
阿新 • • 發佈:2018-12-08
Java圖書管理系統練習程式(三)
本部分內容主要實現將使用者資訊寫入檔案中,並在程式執行時,將檔案中的使用者資訊讀入到記憶體中,實現使用者資訊的儲存。
將Java物件序列化後,可以將物件儲存在檔案中,或者在網路中直接進行傳輸。
如果要實現序列化,只需讓該類實現Serializable介面即可。該介面只是一個標記介面,不需要實現任何方法,它只是表明該類的例項化物件是可以序列化的。
一、將Java物件通過序列化實現讀寫
1.建立ObjectOutputStream輸出流
File file=new File("user.txt"); ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file,false));
其中的file,表示儲存資料的檔案;false表示是否追加
2.將序列化物件輸出到檔案中
oos.writeObject(users); oos.flush();//重新整理方法,將資料立刻輸出,或者等到流內滿了自動呼叫flush重新整理,將資料輸出
3.關閉ObjectOutPutStream物件
oos.close();
4.建立ObjectInputStream輸入流
File file=new File("user.txt"); ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
5.讀取序列化物件
ois.readObject();
6.關閉ObjectOutPutStream物件
ois.close();
二、在util包中建立FileRw類,實現對使用者物件集合的檔案讀寫操作
package sky.book.util; import sky.book.bean.User; import java.io.*; import java.util.List; public class FileRW { /** * 將使用者集合物件寫入到檔案中 * @param users * @return */ public static boolean writeDateToFile(List<User> users){ File file=new File("user.txt"); try { ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file,false)); oos.writeObject(users); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public static List<User> readDateFromFile(){ File file=new File("user.txt"); ObjectInputStream ois=null; List<User> users=null; try { ois=new ObjectInputStream(new FileInputStream(file)); users= (List<User>) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } return users; } }