对象流:简单来说就是讲对象作为流进行读写。该对象的类必须要实现Serializable接口,才能使用对象流操作,也叫能序列化的类。使用ObjectInputStream或ObjectOutputStream来装取对象。常见的String,一些集合类也都是有实现Serializable接口的。
序列化类:
/一个简单类实现Serializable接口
//类中没有被static或transient修饰的属性或方法,都会被序列化
public class Cat1 implements Serializable {
/**
* 这是添加的默认序列化ID,不要乱改哦
* 比如写的时候是一个序列ID,读的时候又是另一个序列ID,两者对比不上就会出现异常
*/
private static final long serialVersionUID = 1L;
private String name = "默认";
public Cat1(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类:
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public static void main(String[] args) {
// fun1();
fun2();
}
//演示ObjectOutputStream
public static void fun1(){
ObjectOutputStream oos = null;
Cat1 c1 = new Cat1("红红");
Cat1 c2 = new Cat1("花花");
try {
oos = new ObjectOutputStream(new FileOutputStream("f:\\test1.txt"));
//ObjectOutputStream写入对象的方法
oos.writeObject(c1);
oos.writeObject(c2);
System.out.println("写入成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//演示ObjectInputStream
public static void fun2(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("F:\\test1.txt"));
Cat1 c = null;
while((c = (Cat1) ois.readObject()) != null){
System.out.println(c.getName());
}
} catch (EOFException e) { //这个用来处理ois.readObject读到文件尾部的异常
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭流
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}