对象序列化文件的追加

今天学习对象序列化的时候,自己每次写入同一个文件,读取的时候只能读到第一次写入的Object,读取后面写入的Object都会报java.io.StreamCorruptedException错误,经过搜索,发现每次写入对象的时候,Java默认的对象序列化都会在每次写入前写入一个四个字节的头。因此,在对象追加的时候就需要把头去掉。代码如下:
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

public static void main(String[] args) throws EOFException{
    Person per = new Person();
    per.setName("ysj");
    per.setAge(23);
    ObjectInputStream in = null;
    ObjectOutputStream out = null;
    FileOutputStream ostream = null;
    try {
        File file = new File("persons.txt");
        if( file.exists() ){
            ostream = new FileOutputStream(file,true);
            out = new ObjectOutputStream(ostream);
            long pos =  ostream.getChannel().position() - 4;
            ostream.getChannel().truncate(pos);
        }else{
            file.createNewFile();
            ostream = new FileOutputStream(file);
            out = new ObjectOutputStream(ostream);
        }
        out.writeObject(per);
        in = new ObjectInputStream(
                new FileInputStream("persons.txt"));
        while( true ){
            Person p = (Person) in.readObject();
            System.out.println(p.getName() + ":" + p.getAge());
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e){
        if( e instanceof EOFException ){
            System.out.println("对象读取完毕!");
        }else{
            e.printStackTrace();
        }
    } finally{
        if( out != null ){
            try{
                out.close();
            }catch(IOException e){
                e.printStackTrace();
            }
            out = null;
        }
        if( ostream != null ){
            try{
                ostream.close();
            }catch(IOException e){
                e.printStackTrace();
            }
            ostream = null;
        }
        if( in != null ){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            in = null;
        }
    }
}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值