Java—IO流 对象的序列化和反序列化
序列化的基本操作
1.对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化。
2.序列化流(ObjectOutputStream),writeObject 方法用于将对象写入输出流中;
反序列化流(ObjectInputStream),readObject 方法用于从输入流中读取对象。
3.序列化接口(Serializeable)
对象必须实现序列化接口,才能进行序列化,否则会出现异常。这个接口没有任何方法,只是一个标准。
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);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。