IO操作-ObjectInputStream演示

来源:互联网 发布:加拿大地缘政治知乎 编辑:程序博客网 时间:2024/06/06 18:16
对象流:简单来说就是讲对象作为流进行读写。该对象的类必须要实现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();}//演示ObjectOutputStreampublic 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();}}}}//演示ObjectInputStreampublic 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//关闭流if(ois != null){try {ois.close();} catch (IOException e) {e.printStackTrace();}}}}




原创粉丝点击