Java序列化 如何把多个对象存储在一个文件中


/**
 * 用于保存模板文件,内容包括:
 * 1,标志位,1 int
 * 2,版本   1 int
 * 3,数据头长度 1 int
 * 4,预留数据头空间  5120 byte
 * 5,后续数据长度  0不存在,>0存在
 * 7,后续数据
 * @author benson
 *
 */
import java.io.*;

public class BTemplateFile {
    private static final int FLAG = -1;
    private static final int HEAD_LENGTH = 5120;
    private byte[] head = null;
    private static BTemplateFile instance;
    
    //单例模式
    public static synchronized BTemplateFile getInstance(){
        if (instance == null) {
          instance = new BTemplateFile();
        }
        return instance;
      }

    /**
     * 构造函数
     */
    private BTemplateFile() {
        super();
        // TODO Auto-generated constructor stub
        head = new byte[HEAD_LENGTH];
        for (int i = 0; i < HEAD_LENGTH; i++) {
            head[i] = (byte) 0xff;
        }
    }

    /**
     * 创建一个空白的模板文件
     *
     * @param version
     * @param filename
     * @throws IOException
     */
    public void create(File file) throws IOException {
        if (!file.exists()) {
            FileOutputStream _out = new FileOutputStream(file);

            DataOutputStream _data_out = new DataOutputStream(_out);
            _data_out.writeInt(FLAG); // 写入标志
            _data_out.writeInt(0); // 写入版本
            _data_out.writeInt(0); // head_length
            _data_out.write(head);
            _data_out.writeInt(0); // 无后续数据
            _data_out.write(head); // 填充2000个字节的空数据
            _data_out.close();
            _out.close();
        }
    }

    /**
     * 读取head
     *
     * @param filename
     * @return
     * @throws Exception
     */
    public Object read_head(File file) throws Exception {
        if(!file.exists()){
            throw new Exception("读取模板文件不存在!");
        }
        Object obj = null;
        DataInputStream _in = new DataInputStream(new FileInputStream(file));
        int flag = _in.readInt();
        int version = _in.readInt();
        if (flag != FLAG) {
            _in.close();
            throw new Exception("文件格式错误!");
        }

        if (version == 0) {
            int head_length = _in.readInt();
            if (head_length > 0) {
                ObjectInputStream _obj_in = new ObjectInputStream(_in);
                obj = _obj_in.readObject();
            }
        }
        _in.close();
        return obj;
    }

    /**
     * 读取数据对象
     *
     * @param filename
     * @return
     * @throws Exception
     */
    public Object read_data(File file) throws Exception {
        if(!file.exists()){
            throw new Exception("读取模板文件不存在!");
        }
        Object obj = null;
        DataInputStream _in = new DataInputStream(new FileInputStream(file));
        int flag = _in.readInt();
        int version = _in.readInt();

        if (flag != FLAG) {
            _in.close();
            throw new Exception("文件格式错误!");
        }
        if (version == 0) {
            int head_length = _in.readInt();
            _in.read(head);
            int data_length = _in.readInt();

            if (data_length > 0) {
                ObjectInputStream _obj_in = new ObjectInputStream(_in);
                obj = _obj_in.readObject();
            }
        }
        _in.close();
        return obj;
    }

    /**
     * 修改头信息
     *
     * @param head_str
     * @throws Exception
     */
    public void modify_head(Object head_obj,File file) throws Exception {
        if(!file.exists()){
            throw new Exception("读取模板文件不存在!");
        }
        RandomAccessFile rfile = new RandomAccessFile(file, "rw");
        int flag = rfile.readInt();
        int version = rfile.readInt();
        if (flag != FLAG) {
            rfile.close();
            throw new Exception("文件格式错误!");
        }
        if (version == 0) {
            ByteArrayOutputStream _out = new ByteArrayOutputStream();
            ObjectOutputStream _obj_out = new ObjectOutputStream(_out);
            _obj_out.writeObject(head_obj);
            _obj_out.flush();
            byte[] head_bytes = _out.toByteArray();
            if (head_bytes.length < HEAD_LENGTH) {
                rfile.writeInt(head_bytes.length);
                rfile.write(head_bytes);
            } else {
                rfile.close();
                throw new Exception("头长度超过限制(" + HEAD_LENGTH + ")="
                        + head_bytes.length);
            }
        }
        rfile.close();
    }

    /**
     * 修改数据对象
     *
     * @param data
     * @param filename
     * @throws Exception
     */
    public void modify_data(Object data, File file) throws Exception {
        if(!file.exists()){
            throw new Exception("读取模板文件不存在!");
        }
        RandomAccessFile rfile = new RandomAccessFile(file, "rw");
        int flag = rfile.readInt();
        int version = rfile.readInt();
        if (flag != FLAG) {
            rfile.close();
            throw new Exception("文件格式错误!");
        }
        if (version == 0) {
            int head_length = rfile.readInt();
            rfile.skipBytes(HEAD_LENGTH);
            ByteArrayOutputStream _out = new ByteArrayOutputStream();
            ObjectOutputStream _obj_out = new ObjectOutputStream(_out);
            _obj_out.writeObject(data);
            _obj_out.flush();
            byte[] data_bytes = _out.toByteArray();
            rfile.writeInt(data_bytes.length);
            rfile.write(data_bytes);
            _obj_out.close();
            _out.close();
        }
        rfile.close();
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        BTemplateFile b = new BTemplateFile();
        String filename = "d:\\tmp\\1\\aa.vav";
        File file=new File(filename);
        ClientData data = new ClientData();
        data.setKey(100);
        data.setValue("111111111111111111111111");
        data.setSaveName("中国人民共和国");

        ClientData data1 = new ClientData();
        data1.setKey(3333333);
        data1.setValue("33333333333333");
        data1.setSaveName("到搜房数据发生");

        b.create(file);

        b.modify_head(data1, file);
        System.out.println("1 ------");

        b.modify_data(data, file);
        System.out.println("2 ------");

        ClientData head = (ClientData) b.read_head(file);
        if (head != null)
            System.out.println("head:" + head.getKey() + " " + head.getValue()
                    + " " + head.getSaveName());
        else
            System.out.println("head is null");

        ClientData c = (ClientData) b.read_data(file);
        if (c != null)
            System.out.println("data:" + c.getKey() + " " + c.getValue() + " "
                    + c.getSaveName());
        else
            System.out.println("data is null");
    }

}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值