对象流的读取与写入

时间:2023-01-29 20:59:44

传输对象时,被传输的对象需要实现Serializable的接口,否则会抛出java.io.NoSerializable的异常。


public class StudentTest {

/**
* 将对象流写入文件
* @param obj
*/
public void write(Object obj){
OutputStream out=null;
ObjectOutputStream objOut=null;
try {
out=new FileOutputStream("obj.txt");
objOut=new ObjectOutputStream(out);
objOut.writeObject(obj);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
objOut.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}
public Object  ReadObj(){
InputStream in=null;
ObjectInputStream obin=null;
try {
in=new FileInputStream("obj.txt");
obin=new ObjectInputStream(in);
Object obj=obin.readObject();
return obj;
} catch (Exception e) {
// TODO Auto-generated catch block

e.printStackTrace();

//用finally语句来关闭流的操作,原则是先调用,后关闭,后调用,先关闭。

}finally{
try {
obin.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return null;
}