流对象:用于存储对象的流。(创建一个对象后,默认是存在堆内存中的,如果想要把对象存入到文件中,就需要用到流对象)
ObjectInputStream:对象输入流。
ObjectOutputStrem:对象输出流。
存入到对象的流必须要被序列化(也就是这个类要实现serializable接口)。
下面通过代码演示流对象以及序列化。
//创建一个对象,实现序列化接口。
public class Person implements Serializable{
//public static final long serialVersionUID = 15L;//设置类的UID,设置UID后,可以修改类的属性以后,流对象在调用对象的时候可以正常运行,否则报错。
private String name;
private int age;
static String contry="cn";//静态函数不会被序列化。(transient表示临时数据,也不会被序列化)
Person(String name,int age,String contry){
this.name = name;
this.age = age;
this.contry = contry;
}
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 toString(){
return name+":"+age+contry;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//操作对象的流
public class ObjectStreamDemo {
public static void main(String[] args)throws Exception {
//writeObj();
readObj();
}
//读取对象流方法。
public static void readObj()throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
//写入对象流的方法。
public static void writeObj()throws IOException{
//创建一个对象写入流,将对象写入到d:\obj.txt文件中。
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("d:\\obj.txt"));
oos.writeObject(new Person("lisi",20,"kr"));
oos.close();
}
}