Java序列化流-ObjectOutputStream、ObjectInputStream

Java对象流的基本概念:

实例代码:

实体类User:

 1 import java.io.Serializable;
 2 
 3 /**
 4  * @author zsh
 5  * @company wlgzs
 6  * @create 2019-01-25 15:11
 7  * @Describe
 8  */
 9 public class User implements Serializable {
10 
11     private Integer id;
12 
13     private String name;
14 
15     public User(Integer id, String name) {
16         this.id = id;
17         this.name = name;
18     }
19 
20     @Override
21     public String toString() {
22         return "User{" +
23                 "id=" + id +
24                 ", name='" + name + '\'' +
25                 '}';
26     }
27 }

Main类:

 1 import java.io.*;
 2 import java.util.ArrayList;
 3 
 4 public class Main {
 5 
 6     public static void main(String[] args) throws IOException, ClassNotFoundException {
 7         //1.定义1个存储user的ArrayList集合
 8         ArrayList<User> list = new ArrayList<>();
 9 
10         //2.往ArrayList集合中存储User对象
11         list.add(new User(1,"张三"));
12         list.add(new User(2,"李四"));
13         list.add(new User(3,"王五"));
14 
15         //3.创建一个序列化流ObjectOutputSteam对象
16         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("t.txt"));
17 
18         //4.使用ObjectOutputSteam对象的方法writeObject,对集合进行序列化
19         oos.writeObject(list);
20 
21         //5.创建一个反序列化流ObjectInputSteam对象
22         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("t.txt"));
23 
24         //6.使用ObjectInputStream对象的方法readObject,读取文件中保存的集合
25         Object o = ois.readObject();
26 
27         //7.把Object类型的集合转换为ArrayList类型
28         ArrayList<User> list2 = (ArrayList<User>) o;
29 
30         //8.遍历ArrayList集合
31         for (User user : list2) {
32             System.out.println(user);
33         }
34 
35         //9.释放资源
36         oos.close();
37         ois.close();
38 
39     }
40 }

项目结构目录:

猜你喜欢

转载自www.cnblogs.com/zsh-blogs/p/10319894.html