Java(31):序列化(01)
阿新 • • 發佈:2020-11-16
package zzz; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; public class SerializationTest { public static void main(String[] args) throws IOException { Student stu= new Student("zzz", "123456", 18); // 序列化:把物件資訊寫入到硬盤裡 // 1.目標檔案位置 File file = new File("f:\\object.ser"); // 2.建立資料通道 FileOutputStream fos = new FileOutputStream(file); // 3.建立輸出流物件 ObjectOutputStream ops = new ObjectOutputStream(fos); // 4.物件輸出到硬碟上ops.writeObject(stu); // 關閉資源 ops.close(); System.out.println(stu); } } class Student implements Serializable { public static final long UID = 123L; private String userName; private String passWord; private int age;public Student(String userName, String passWord, int age) { this.userName = userName; this.passWord = passWord; this.age = age; System.out.println("Student end."); } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return this.userName; } public void setPassWord(String passWord) { this.passWord = passWord; } public String getPassWord() { return this.passWord; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } @Override public String toString() { return "Student: userName="+userName+", passWord="+passWord+", age="+age; } }