java基础之序列化与反序列化

来源:互联网 发布:手机淘宝明星店铺 编辑:程序博客网 时间:2024/06/09 18:45

原理:

 Java序列化是指把Java对象转换为二进制的数据流
Java反序列化是指把字节序列恢复为Java对象的过程。

如何实现序列化?

将需要序列化的类实现Serializable接口就可以了,Serializable接口中没有任何方法,可以理解为一个标记,即表明这个类可以序列化。

代码原理:

private static void read() throws IOException, ClassNotFoundException {// 创建反序列化对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));// 还原对象Object obj = ois.readObject();// 释放资源ois.close();// 输出对象System.out.println(obj);}private static void write() throws IOException {// 创建序列化流对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));// 创建对象Person p = new Person("霞", 27);// public final void writeObject(Object obj)oos.writeObject(p);// 释放资源oos.close();}
具体代码:

1.序列化对象

package com.etc.day16.xulie;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;//序列化对象public class TestDemo_1 {public static void main(String[] args) {ObjectOutputStream oos = null;try { oos = new ObjectOutputStream(new FileOutputStream("e:\\x.txt"));Demo_1 person = new Demo_1("小明",18);oos.writeObject(person);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(oos!=null){try {oos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}
2.反序列化

package com.etc.day16.xulie;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.ObjectInputStream;public class TestDemo_2 {public static void main(String[] args) {//反序列化ObjectInputStream ois = null;// 创建反序列化对象try {ois = new ObjectInputStream(new FileInputStream("e:\\x.txt"));//还原对象Demo_1 person =(Demo_1)ois.readObject();System.out.println(person);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(ois!=null){try {ois.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}


原创粉丝点击