Java IO流对象的序列化和反序列化实例详解

2025-05-29 0 60

JavaIO流 对象的序列化和反序列化

序列化的基本操作

  1.对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化

  2.序列化流(ObjectOutputStream),writeObject 方法用于将对象写入输出流中;

  反序列化流(ObjectInputStream),readObject 方法用于从输入流中读取对象。

  3.序列化接口(Serializeable)

  对象必须实现序列化接口,才能进行序列化,否则会出现异常。这个接口没有任何方法,只是一个标准。

?

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

31

32

33

34

35

36

37

38
package com.test.io;

import java.io.FileInputStream;

import java.io.FileOutputStream;import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class ObjectSerialzeTest {

/**

* 对象的序列化

* @param file

* @throws Exception

*/

public void ObjectOutput (String file) throws Exception {

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));

Student stu = new Student("002", "张四", 12);

oos.writeObject(stu);

oos.flush();

oos.close();

}

/**

* 对象的反序列化

* @param file

* @throws Exception

*/

public void ObjectInput(String file) throws Exception {

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

Student stu = (Student)ois.readObject();

System.out.println(stu.toString());

ois.close();

}

public static void main(String[] args) throws Exception {

String file = "F:\\\\javaio\\\\obj.dat";

ObjectSerialzeTest ost = new ObjectSerialzeTest();

ost.ObjectOutput(file);

ost.ObjectInput(file);

}

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.cnblogs.com/tianxintian22/p/6852284.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java IO流对象的序列化和反序列化实例详解 https://www.kuaiidc.com/116591.html

相关文章

发表评论
暂无评论