对象操作流

该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ObjectOutputStream new ObjectOutputStream(OutputStream), writeObject()
 
public class Demo3_ObjectOutputStream {
 
  public static void main(String[] args) throws IOException {
 
    Person p1 = new Person("张三", 23);
 
    Person p2 = new Person("李四", 24);
 
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));//创建对象输出流
 
    oos.writeObject(p1);
 
    oos.writeObject(p2);
 
    oos.close();
 
  }
 
}

 

 ObjectInputStream

 new ObjectInputStream(InputStream), readObject()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Demo3_ObjectInputStream {
 
  public static void main(String[] args) throws IOException, ClassNotFoundException {
 
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
 
    Person p1 = (Person) ois.readObject();
 
    Person p2 = (Person) ois.readObject();
 
    System.out.println(p1);
 
    System.out.println(p2);
 
    ois.close();
 
  }
 
}

 对象操作流优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Person p1 = new Person("张三", 23);
 
Person p2 = new Person("李四", 24);
 
Person p3 = new Person("马哥", 18);
 
Person p4 = new Person("辉哥", 20);
 
ArrayList<Person> list = new ArrayList<>();
 
list.add(p1);
 
list.add(p2);
 
list.add(p3);
 
list.add(p4);
 
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f.txt"));
 
oos.writeObject(list); //写出集合对象
 
oos.close();

 

posted on   LoaderMan  阅读(200)  评论(0)    收藏  举报

< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

导航

统计

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示