Java 提供了对象流ObjectlnputiStream 和 ObjectOutputStream,可以将以对象方式存在于内中的数据存储至文件,需要时再将其从文件中读出还原为对象,或者在网络上传送对象。
1.序列化的作用
序列化指把内存中的Java对象转换成与平台无关的二进制字节序列,以便永久保存在性盘上或通过网络进行传输,是Java提供的一种将对象写人到输出流并在之后将其读回的机制。
2.什么是序列化和反序列化
把Java对象转化为字节序列的过程称为对象的序列化,把字节序列恢复为Java对象的过程称为反序列化。
3.可以序列化的标志
如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的。为了要某个类似可序化的,该类可以通过实现Serializable接口,接口内无具体方法,只需要声明实现该接口,该接口只具有标识性的意义,我代表该对象是可以序列化的。
例:
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID=1l;
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
}
凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态常量serialVersionUID,用来表明类的不同版本间的兼容性。如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化,故此常量建议大家显示声明。
通过ObjectOutputStream类对象的writeObject()方法,将指定的对象进行序列化,把得到的字节序列写到目标输出流中;通过ObjectInputStream类对象的readObject()方法从源输入流中读取序列,在反序列化为对象,并将其返回。
以下是简单的对象序列化:
序列化:
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID=1l;
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
ObjectOutputStream oos=null;
FileOutputStream fos=null;
try {
fos=new FileOutputStream("D:\\1234.java");
oos=new ObjectOutputStream(fos);
oos.writeObject(new Person("懒大王",18));
oos.flush();
oos.writeObject(new Person("喜羊羊",19));
oos.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
finally{
if(oos!=null) {
try {
oos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
反序列化:
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID=1l;
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "姓名:"+name+" "+"年龄:"+age;
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Main {
public static void main(String[] args) {
ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream("D:\\1234.java"));
try {
Person p=(Person)ois.readObject();
Person p1=(Person)ois.readObject();
System.out.println(p);
System.out.println(p1);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
finally {
if(ois!=null) {
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
注:
1.序列化和反序列化的serialVersionUID相同。
2.反序列化时需要重写toString()方法,负责返回的是对象地址。