public class Student implements Serializable {
private String name;
private int eng;
private int math;
// transient 欄位,表示不進行序列化
private transient int total;
public Student(String name, int eng, int math) {
this.name = name;
this.eng = eng;
this.math = math;
}
public int getTotal() {
return total = eng + math;
}
@Override
public String toString() {
return "\nStudent: "
+ "\nname: " + name
+ "\n eng: " + eng
+ "\n math: " + math
+ "\ntotal: " + getTotal();
}
}
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class StudentOutput {
public static void main(String[] args) {
StudentClass sc = new StudentClass();
sc.add(new Student("Brook", 50, 50));
sc.add(new Student("Chloe", 100, 100));
sc.add(new Student("Jason", 10, 20));
//使用AutoCloseable來避免檔案沒有關閉的問題,使用ObjectOuputStream 輸出資料流
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/Users/user/Desktop/JavaTest/Student.ser"))) {
oos.writeObject(sc);
} catch (Exception e) {
System.err.println(e);
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StudentInput {
public static void main(String[] args) {
//使用AutoCloseable來避免檔案沒有關閉的問題,使用ObjectInputStream 讀取資料流
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:/Users/user/Desktop/JavaTest/Student.ser"))) {
StudentClass sc = (StudentClass) ois.readObject();
System.out.println(sc.getList());
} catch (IOException e) {
System.err.println(e);
} catch (ClassNotFoundException ex) {
System.err.println(ex);
}
}
}