package com.itheima.d5_serializable; import java.io.Serializable; ### // 类的对象如果要序列化,必须实现Serializable接口。 public class User implements Serializable { private int id; private String loginName; private String passWord; private String hobby; public User(){ } public User(int id, String loginName, String passWord, String hobby) { this.id = id; this.loginName = loginName; this.passWord = passWord; this.hobby = hobby; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "User{" + "id=" + id + ", loginName='" + loginName + '\'' + ", passWord='" + passWord + '\'' + ", hobby='" + hobby + '\'' + '}'; } }
package com.itheima.d5_serializable; import java.io.*; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) throws Exception { // 目标:序列化多个对象,反序列化多个对象。 List标签:loginName,String,对象,public,集合,hobby,序列化,id,passWord From: https://www.cnblogs.com/sisiyibailiu/p/16967236.htmlusers = new ArrayList<>(); users.add(new User(1, "唐僧0", "baigujing", "赶走孙悟空")); users.add(new User(2, "唐僧1", "baigujing1", "赶走孙悟空1")); users.add(new User(3, "唐僧2", "baigujing2", "赶走孙悟空2")); users.add(new User(4, "唐僧3", "baigujing3", "赶走孙悟空3")); // 直接序列化集合对象。 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day11-special-file-log/src/data.txt")); oos.writeObject(users); oos.close(); // 反序列化 getUsers(); } public static void getUsers() throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day11-special-file-log/src/data.txt")); List users = (List ) ois.readObject(); for (User u : users) { System.out.println(u); } ois.close(); } }