[Java] java对象序列化 永久保存到硬盘 →→→→→进入此内容的聊天室

来自 , 2020-01-26, 写在 Java, 查看 118 次.
URL http://www.code666.cn/view/ba386660
  1. import java.io.*;
  2.  
  3. public class SerializableDemo {
  4.         public static void main(String args[]) throws IOException,
  5.                         ClassNotFoundException {
  6.                 Student stu = new Student(1564163, "xxx", 18, "CSD");
  7.                 FileOutputStream fo = new FileOutputStream("data.ser");
  8.                 // 保存对象的状态
  9.                 ObjectOutputStream so = new ObjectOutputStream(fo);
  10.                 try {
  11.                         so.writeObject(stu);
  12.                         so.close();
  13.                 } catch (IOException e) {
  14.                         System.out.println(e);
  15.                 }
  16.                 FileInputStream fi = new FileInputStream("data.ser");
  17.                 ObjectInputStream si = new ObjectInputStream(fi);
  18.                 // 恢复对象的状态
  19.                 try {
  20.                         stu = (Student) si.readObject();
  21.                         si.close();
  22.                 } catch (IOException e) {
  23.                         System.out.println(e);
  24.                 }
  25.  
  26.         }
  27. }
  28.  
  29. class Student implements Serializable {
  30.         int id; // 学号
  31.         String name; // 姓名
  32.         int age; // 年龄
  33.         String department; // 系别
  34.  
  35.         public Student(int id, String name, int age, String department) {
  36.                 this.id = id;
  37.                 this.name = name;
  38.                 this.age = age;
  39.                 this.department = department;
  40.         }
  41. }
  42.  

回复 "java对象序列化 永久保存到硬盘"

这儿你可以回复上面这条便签

captcha