172. 階乘後的零
阿新 • • 發佈:2022-03-26
記住一句話 序列化儲存起來是用來 使用的, 不是用來看的
物件序列化的含義是什麼?
把物件資料存入到檔案中去
物件序列化用了哪個流?
物件位元組輸出流 ObjectOutputStream
方法Public void writeObject(Object obj)
序列化物件的要求是什麼樣的?
物件必須實現序列化介面
物件位元組輸出流
public class ObjectOutputStreamDome1 {
public static void main(String[] args) throws Exception{
//1. 建立學生物件
Student s = new Student("陳雷","chenlei","1314520",21);
//2. 物件序列化: 使用物件位元組輸出流包裝位元組輸出流管道
OutputStream os = new FileOutputStream("E:\\idea_java_project\\io_project\\src\\dataCHEN.txt");
ObjectOutputStream oos = new ObjectOutputStream(os);
//3.直接呼叫序列化方法
oos.writeObject(s);
//4.釋放資源
oos.close();
}
}
class Student implements Serializable{ //物件如果要序列化, 必須要實現Serializable介面
private String name;
private String loginName;
private String passWord;
private int age;
----------------------------------------------------------
反序列化
/*
目標: 學會進行物件反序列化:使用物件位元組流把檔案中的物件資料恢復成記憶體中的Java物件
*/
public class ObjectInputStreamDemo2 {
public static void main(String[] args) throws Exception{
//1. 建立物件位元組輸入流管道 包裝低階的位元組輸入流管道
InputStream is = new FileInputStream("E:\\idea_java_project\\io_project\\src\\dataCHEN.txt");
ObjectInputStream ois = new ObjectInputStream(is);
//2. 呼叫物件位元組輸入流方法
Student s = (Student) ois.readObject();
System.out.println(s);
}
}