对象存储--ObjectOutputStream和ObjectInputStream

代码

package com.foot.lesson03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SaveObject {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        List<StudentSave> list = new ArrayList<StudentSave>(5);
        list.add(new StudentSave("张三", "s201532", 11));
        list.add(new StudentSave("李四", "s256489", 25));
        list.add(new StudentSave("王五", "s223598", 69));
        list.add(new StudentSave("雪舞", "s145862", 3));
        list.add(new StudentSave("霓虹", "s256987", 45));
        //创建一个文件,存入相关的内容
        File file = new File("H:\\saveObject.so");
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);//如果想实现不断在后面续加,将需要重写一个类
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(list);
            oos.flush();
            oos.close();
            fos.close();
            //读出该文件,进行显示
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            List<StudentSave> inputList = null;
            //读出数据,显示
            inputList = (List<StudentSave>)ois.readObject();
            int i = 0;
            for (StudentSave studentSave : inputList) {
                i++;
                System.out.println(i + ":--" + studentSave.getName() + "---" + studentSave.getSno() + "---" + studentSave.getAge());
            }
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

class StudentSave implements Serializable {// 该类必须实现Serializable接口,否则不能实现存储
    private static final long serialVersionUID = -9059721037598130156L;

    private String name;
    private String sno;
    private int age;

    public StudentSave(String name, String sno, int age) {
        this.name = name;
        this.sno = sno;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

说明 ##

如果想实现文中提到的需要在文件尾部不断加入序列化对象,可以参考以下方法:该内容转自于 https://blog.csdn.net/xjl456852/article/details/50855878。如需看的清晰

使用ObjectOutputStream,如果以追加的方式,在一个文件中末尾追加写入object,那每次都会在写入时增加特定的文件头信息,而这些头信息如果每次都写入到文件中,在使用ObjectInputStream读取这个文件object时就会出现异常.

java.io.StreamCorruptedException: invalid type code: AC

而文件的头信息格式是这样的:AC ED 00 05
这个头信息只能出现在整个文件的头部,且仅出现一次.

所以在一个文件中追加写入Object,就需要自定义自己的类来实现.

package com.xjl456852.process;



import org.junit.Test;

import javax.script.ScriptException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xjl456852 on 2016/3/11.
 */
public class ObjectTest {
    /**
     * 使用ObjectOutputStream写Object对象,不追加的情况,这个是可以的.
     * @throws ScriptException
     * @throws IOException
     */
    @Test
    public void testObject() throws ScriptException, IOException {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            String file = "d:/xjl/object.txt";
            //使用ObjectOutputStream追加写入,在多次写完之后,读取object信息时会有异常.所以不能这样写.
//            oos = new ObjectOutputStream(new FileOutputStream(new File(file),true));
            oos = new ObjectOutputStream(new FileOutputStream(new File(file)));

            List<Map<Integer,String>> list = new ArrayList<Map<Integer,String>>();
            Map<Integer, String> map = new HashMap<>();
            map.put(1, "xjl");
            map.put(2, "xjl");
            list.add(map);
            oos.writeObject(list);
            oos.flush();

            List<Map<Integer,String>> list2 = new ArrayList<Map<Integer,String>>();
            Map<Integer, String> map2 = new HashMap<>();
            map2.put(3, "xjl3");
            map2.put(4, "xjl4");
            list2.add(map2);
            oos.writeObject(list2);
            oos.flush();

            ois = new ObjectInputStream(new FileInputStream(new File(file)));
            List<Map<Integer,String>> listResult = (List<Map<Integer,String>>)ois.readObject();
            List<Map<Integer,String>> listResult2 = (List<Map<Integer,String>>)ois.readObject();

            printList(listResult);
            printList(listResult2);



        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(oos != null) {
                oos.close();
                oos = null;
            }
            if(ois != null) {
                ois.close();
                ois = null;
            }
        }
    }

    /**
     * 使用自定义的方式,在同一个文件中追加Object,要使用下面的方式
     * @throws ScriptException
     * @throws IOException
     */
    @Test
    public void testObject2() throws ScriptException, IOException {

        ObjectInputStream ois = null;
        try {
            String file = "d:/xjl/object2.txt";

            List<Map<Integer,String>> list = new ArrayList<Map<Integer,String>>();
            Map<Integer, String> map = new HashMap<>();
            map.put(1, "xjl");
            map.put(2, "xjl");
            list.add(map);
            writeObject(list,file);

            List<Map<Integer,String>> list2 = new ArrayList<Map<Integer,String>>();
            Map<Integer, String> map2 = new HashMap<>();
            map2.put(3, "xjl3");
            map2.put(4, "xjl4");
            map2.put(5, "xjl4");
            list2.add(map2);
            writeObject(list2,file);


            ois = new ObjectInputStream(new FileInputStream(new File(file)));
            List<Map<Integer,String>> listResult = (List<Map<Integer,String>>)ois.readObject();
            List<Map<Integer,String>> listResult2 = (List<Map<Integer,String>>)ois.readObject();

            printList(listResult);
            printList(listResult2);

        } catch(Exception e) {
            e.printStackTrace();
        } finally {

            if(ois != null) {
                ois.close();
                ois = null;
            }
        }
    }

    /**
     * 
     * 
     * 如果在文件中追加对象,每次创建ObjectOutputStream,都会在每次写入时增加header信息.
     * 导致读取时出现java.io.StreamCorruptedException: invalid type code: AC异常
     * @param t
     * @param file
     * @param <T>
     * @throws IOException
     */
    public <T>void writeObject (T t, String file) throws IOException {

        ObjectOutputStream oos = null;
        try {
            oos = MyOutputStream.newInstance(file);
            oos.writeObject(t);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(oos != null) {
                oos.close();
                oos = null;
            }
        }

    }

    public static void printList(List<Map<Integer, String>> list) {
        for(Map<Integer,String> map : list) {
            for(Map.Entry<Integer,String > entry : map.entrySet()) {
                System.out.println(entry.getKey() +":"+ entry.getValue());
            }
        }
    }
}

下面的是自己实现的追加写入Object信息到文件中类:

package com.xjl456852.process;

import java.io.*;

/**
 * Created by xjl456852 on 2016/3/11.
 */

/**
 * 使用自定义的方式,来实现追加写入object
 */
public class MyOutputStream extends ObjectOutputStream {

    public MyOutputStream(OutputStream out) throws IOException {
        super(out);// 会调用writeStreamHeader() 
    }

    /**
     * 覆盖父类的方法,使其在已有对象信息并追加时,不写header信息
     * 查看源码会发现:writeStreamHeader方法会写入以下两行内容:
     * 
     *  bout.writeShort(STREAM_MAGIC);
     *  bout.writeShort(STREAM_VERSION);
     *  
     *  这两行对应的值:
     *  final static short STREAM_MAGIC = (short)0xaced;
     *  final static short STREAM_VERSION = 5;
     *  
     *  在文件中头部就会写入:AC ED 00 05
     *  一个文件对象只有在文件头出应该出现此信息,文件内容中不能出现此信息,否则会导致读取错误
     *  所以在追加时,就需要覆盖父类的writeStreamHeader方法,执行reset()方法
     *  
     *  reset()方法写入的是这个:final static byte TC_RESET =        (byte)0x79;
     * @throws IOException
     */
    @Override
    protected void writeStreamHeader() throws IOException {
        super.reset();
    }

    public static ObjectOutputStream newInstance(String file) throws IOException {
        File f = new File(file);
        long length = f.length();
        ObjectOutputStream oos = null;
        if(f.length() == 0) {
            oos = new ObjectOutputStream(new FileOutputStream(new File(file),true));
        } else {
            oos = new MyOutputStream(new FileOutputStream(new File(file),true));
        }
        return oos;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值