对象的序列化主要有两种用途:
1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
2) 在网络上传送对象的字节序列。
如果现在要想实现对象序列化,必须让一个类去实现java.io.Serializable 接口。但是这个接口里面没有定义任何的方法。因为这是一个标识接口,表示的是一种能力,指的是类对象可以被序列化的能力。
★ . 实现对象的序列化使用ObjectOutputStream 类完成。
· 构造方法:
public ObjectOutputStream(OutputStream out) throws IOException
· 输出对象的方法:
public final void writeObject(Object obj) throws IOException
★ . 将序列化的数据再读取回来,就使用反序列化操作,利用ObjectInputStream 类完成。
· 构造方法:
public ObjectInputStream(InputStream in) throws IOException
· 读取对象的方法 :
public final Object readObject() throws IOException,ClassNotFoundException
eg : 序列化和反序列化的示例 :
package example;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* 对象流
*/
class Book implements Serializable{
//默认情况下,序列化操作会将所有的属性都进行保存
//若加上transient关键字可以使属性不被序列化
private transient String title;
private double price;
public Book() {
}
public Book(String title,double price){
this.title = title;
this.price = price;
}
@Override
public String toString() {
return "书名:" + this.title + ",价格:" + this.price;
}
}
public class TestDemo {
public static void main(String[] args) throws Exception {
File file = new File("e:\\demo\\test.txt");
//序列化操作
// if(!file.getParentFile().exists()) {
// file.getParentFile().mkdirs();
// }
// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
// oos.writeObject(new Book("Java核心技术开发",20.5));
// oos.close();
//反序列化操作
if(file.exists()){
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
System.out.println(ois.readObject());
ois.close();
}
}
}
▲ . 对于实现Serializable接口的类来说都会有一个警告信息 . 是关于SerialVersionUID的警告 .