Java的序列化流和反序列化流
Java的序列化流和反序列化流
序列化:利用ObjectOutputStream,把对象的信息,按照固定的格式转成一串字节值输出并持久保存到磁盘
反序列化:利用ObjectInputStream,读取磁盘中之前序列化好的数据,重新恢复成对象
package com.cnblogs;
import java.io.*;
/*
本类用于测试序列化和反序列化
*/
/*
序列化:是指把程序中的Java对象,永久保存到磁盘中,相当于写出的过程对应流的方向:out,对应的序列化流为:
ObjectOutputStream
反序列化:是指把之前已经序列化的在文件中保存的数据,读取/恢复到程序对应流的方向:in,对应的反序列化流为:
ObjectInputStream
*/
public class TestSerializable {
public static void main(String[] args) {
method();//序列化
method2();//反序列化
}
private static void method() {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("E:\\ready\\1.txt"));
System.out.println("序列化成功!!!");
Student student = new Student("柒",21,"泰州",'男');
out.writeObject(student);//传入对象
} catch (IOException e) {
System.out.println("很抱歉,序列化失败!!!");
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void method2() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("E:\\ready\\1.txt"));
Object o = in.readObject();
System.out.println(o);
System.out.println("反序列化成功!!!");
} catch (Exception e) {
System.out.println("反序列化失败!!!");
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cnblogs;
import java.io.Serializable;
/*
本类用于封装学生类
*/
/*
如果本类想完成序列化,必须实现可序列化接口,否则会报错:
NotSerializableException: cn.tedu.serializable.Student
Serializable接口是一个空接口,里面一个方法都没有,
作用用来标记,标记这个类对象可以被序列化输出
*/
public class Student implements Serializable{
// private static final long serialVersionUID = 1l; 手动写的UID
private String name;//姓名
private int age;//年龄
private String addr;//住址
private char gender;//性别
public Student() {
System.out.println("我是student类的无参构造");
}
public Student(String name, int age, String addr, char gender) {
System.out.println("我是student类的全参构造");
this.name = name;
this.age = age;
this.addr = addr;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
//重写toString方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", addr='" + addr + '\'' +
", gender=" + gender +
'}';
}
}