关于java对象流如何追加对象总结

做课程设计,卡在这里卡了一天,太难了,经过无数的百度,博客等等等等,还好是解决了,总结一下
注意: 当我们使用对象流的时候,我们向文件中写入或者是读出都是用的序列化对象,而序列化对象在写入文件时,系统会自动添加aced 0005的一个头部,并且占4个字节,这个我在网上看到的,经过验证确实如此。
解决: 我们只需要在写入文件的时候判断该文件是否已经存在,或者说是否已经写入过对象了,如果写入过对象,我们把前面那个4个字节去掉在写入到文件里就OK了
上代码(Recording是一个序列化的类,自己随便弄个类验证即可)

import java.io.*;
public class test {
 public static void main(String args[]){
  File file = new File("text.txt");
  Recording r[] = new Recording[10];
   boolean isexist=false;//定义一个用来判断文件是否需要截掉头aced 0005的
         try{
         if(file.exists()){    //文件是否存在
                isexist=true;
                FileOutputStream fo=new FileOutputStream(file,true);
                ObjectOutputStream oos = new ObjectOutputStream(fo);
                long pos=0;
               if(isexist){
                         pos=fo.getChannel().position()-4;//追加的时候去掉头部aced 0005
                         fo.getChannel().truncate(pos);
                            }
                         oos.writeObject(new Recording("小明","锡纸烫",388,"李四","10.23"));//进行序列化   
                         oos.close();
           }
         else{//文件不存在
              file.createNewFile();
              FileOutputStream fo=new FileOutputStream(file);
              ObjectOutputStream wr1 = new ObjectOutputStream(fo);
              wr1.writeObject(new Recording("小花","纹理烫",288,"张三","10.23"));
     wr1.writeObject(new Recording("小明","锡纸烫",388,"李四","10.23"));
     wr1.writeObject(new Recording("小刚","洗发",18,"张三","10.23"));
     wr1.writeObject(new Recording("小强","洗发",18,"张三","10.23"));
     wr1.writeObject(new Recording("小明","洗发",18,"张三","10.23"));
     wr1.close(); // 写入操作完成
           }
   FileInputStream in = new FileInputStream(file);
   ObjectInputStream re = new ObjectInputStream(in);
   Recording test = null;
   while((test = (Recording)re.readObject()) != null){
    System.out.println(test.name);
   }
   re.close();
  }
  catch(IOException e){} 
  catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}
发布了32 篇原创文章 · 获赞 5 · 访问量 862

猜你喜欢

转载自blog.csdn.net/shizhuba/article/details/102712842