ObjectInputStream和ObjectOutputStream类创建的对象被称为对象输入流和对象输出流。
创建文件输出流代码:
File file = new File("D:" +File.separator+"student.txt");
OutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(outputStream);
创建文件输入流代码:
File file = new File("D:"+ File.separator+"student.txt");
InputStream inputStream = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(inputStream);
知识储备:
对象序列化:把一个对象变成二进制的数据流的一种方法,可以方便地实现对象地传输或存储;
如果一个类的对象想被序列化,则对象所在的类必须实现java.io.Serializable接口,表示一个类具备了被序列化的能力
接口的定义如下:public interface Serializable{}
此接口没有任何方法,是一个标识接口,表示一个类具备了被序列化的能力
定义被序列化的类
import java.io.Serializable
private class Person implemets Serializable{
private static final long serialVersionUID=1L;
private String name;
private int age;
public Person (String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return ”姓名“+this.name”+“年龄”+“this.age";
}
以上的Person类已经实现了序列化接口,如果要完成对象的输入和输出,必须要依靠对象输出流(ObjectOutputStream)和对象输出流(ObjectInputStream)对象输出流输出序列化对象的步骤有时候也称为序列化,对象输入流读入对象的过程有时也称为反序列化
ps:考虑jdk版本的问题,在序列化操作中会引入了一个serialVersionUID的常量,所以通常在被序列化的类中加入这样一句:
private static final long serialVersionUID=1L;
对象输出流ObjectOutputStream
1.一个对象如果要进行输出,必须要使用OutputStream,此类的定义如下:
public class ObjectOutputStream extends OutputStream implements ObjectOutput ,ObjectStreamConsants
2.此类的方法:1) public ObjectOutputStream(OutputStream out)throws IOException
2)public final writeObject(Object obj)throws IOException
将Person类保存在文件中:
public class SerDemo1{
public static void main(String[] args) throws Exception{
File f = new File("D:"+File.separater+"text.txt");
ObjectOutputStream oos = null;
OutputStream out = new FileOutputStream(f);
oos = new ObjectOutputStream(out);
oos.writeObject(new Person("tyy",30));
oos.close();
}
}
对象输入流ObjectOutputStream
1.可以直接把序列化好的对象反序列化,定义如下:
public class ObjectOutputStream extends OutputStream implements ObjectOutput ,ObjectStreamConsants
2.方法:
1)public ObjectInputStream(InputStream in) throws Exception{
2)public final Object readObject()throws Exception
从文件中将Person类反序列化
public class SerDemo2{
public static void main(String[] args) throws Exception{
File f = new File("D:"+File.separater+"text.txt");
ObjectInputStream ois = null;
InputStream in= new FileInputStream(f);
ois = new ObjectInputStream(in);
Object obj = ois.readObject();
ois.close();
System.out.Println(obj);
}
使用对象流写入或读入对象时,要保证对象是序列化的。这是为了保证能把对象写入到文件,并能再把对象读回到程序中的缘故。一个类如果实现了Serializable接口,那么这个类创建的对象就是所谓序列化的对象。
所谓“对象序列化”: 简单一句话:使用它可以象存储文本或者数字一样简单的存储对象。一个应用是,程序在执行过程中突然遇到短电或者其他的故障导致程序终止,那么对象当前的工作状态也就会丢失,这对于有些应用来说是可怕的。用对象序列化就可以解决这个问题,因为它可以将对象的全部内容保存于磁盘的文件,这样对象执行状态也就被存储了,到需要时还可以将其从文件中按原样再读取出来,这样就解决了数据丢失问题。对象序列化可以简单这么实现:为需要被序列化的对象实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。