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");
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章