package cn.xwy.bean;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = -9024236525280431778L;
private String xingming;
private String xuehao;
private String chengji;
public String getXingming() {
return xingming;
}
public void setXingming(String xingming) {
this.xingming = xingming;
}
public String getXuehao() {
return xuehao;
}
public void setXuehao(String xuehao) {
this.xuehao = xuehao;
}
public String getChengji() {
return chengji;
}
public void setChengji(String chengji) {
this.chengji = chengji;
}
public Student(String xingming,String xuehao,String chengji){
this.xingming=xingming;
this.xuehao=xuehao;
this.chengji=chengji;
}
public static void main(String[] args) {
ObjectOutputStream osc = null;
ObjectInputStream osr = null;
Student ss = new Student("悟空", "007", "95.5f");
Student ss2 = null;
try
{
FileOutputStream wsc = new FileOutputStream("d:/ccc.txt");
osc = new ObjectOutputStream(wsc);
osc.writeObject(ss);
wsc.close();
osr = new ObjectInputStream(new FileInputStream("d:/ccc.txt"));
ss2 = (Student)osr.readObject();
System.out.println("姓名:"+ss2.xingming);
System.out.println("学号:"+ss2.xuehao);
System.out.println("成绩:"+ss2.chengji);
}
catch (Exception e)
{
System.out.println("出现错误");
}
finally
{
try
{
osc.flush();
osc.close();
osr.close();
System.exit(-1);
}
catch (Exception e)
{
System.exit(-1);
}
}
}
}
好吧 , 我也研究了下.
要等文件写入完成后, 再关闭(wsc.close出错) 否则会报错.
try
{
osc.close();
osr.close();
System.exit(-1);
}
应该是System.exit(0)吧;
还有transient 修饰的变量应该不会被写到文件中
补充:
只要关闭最外层的流就好了。Java的IO用了装饰器模式,最外层的流关闭的时候也会调用内层流关闭的方法
wsc在try里面 finally是调不到的 ,只能在catch 之前调用wsc.close()
如果想在finally里调。 要在try- catch块外面 先定义变量 FileOutputStream wsc = null;
然后 finally里要做判断 if(wsc!= null)wsc.close();
osc osr 也是一样。
对象序列化用于保存对象和读取对象,里面应该是一些二进制,你可以用十六进制软件查看器进行查看。读写操作可以用字符流或者字节流!
你的代码里没有wsc.close啊