Summary on how to append objects to java object stream

Doing course design, stuck here for a day, too difficult, after countless Baidu, blogs, etc., fortunately, it is solved, summarize the
note: when we use object streaming, we write to the file Or it is a serialized object that is used for reading, and when the serialized object is written to the file, the system will automatically add a header of aced 0005 and occupies 4 bytes. This I have seen on the Internet has been verified It is true.
Solution: We only need to determine whether the file already exists when writing the file, or whether the object has been written, if the object has been written, we remove the previous 4 bytes and write it to the file OK the
above code (Recording is a serialized class, you can just make a class verification yourself)

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();
  }
 }
}
Published 32 original articles · praised 5 · visits 862

Guess you like

Origin blog.csdn.net/shizhuba/article/details/102712842