|
ObjectInputStream: 把文件格式化为对象输入流,然后读取出对象,但前提对应的类要求实现序列化接口(Serializable) ObjectoutputStream:对象输出流,操作与ObjectInputStream相似. OK,下面就写段简单代码来说明上面两个流的使用. 先是一个实现Serializable序列化接口的类: package com.hj.io; import java.io.Serializable; public class Users implements Serializable{ private int sid; private String name; public Students(int sid, String name) { super(); this.sid = sid; this.name = name; } }
然后就一个ObjectoutputStream流操作类: class WriteObjectIO{ public void test throws Exception{ Users S=new Users(11,"afdsafd"); FileOutputStream fout=new FileOutputStream("d:/1.txt"); ObjectOutputStream obout=new ObjectOutputStream(fout); obout.writeObject(S); obout.close(); fout.close(); } } 这样就把Users的一个对象写入到文件1.txt中去了. OK,最后我们再写个类,又把写入的对象读取出来: class ReadObjectIO{ public void test throws Exception{ File f=new File("d:/1.txt"); FileInputStream input=new FileInputStream(f); ObjectInputStream objectinput=new ObjectInputStream(input);
Object o=objectinput.readObject(); Students s=(Students)o;
System.out.println(s); objectinput.close(); input.close(); } } OK,以上就是对象流的简单操作.
|
一共有 1 条评论