妖碧落

导航

对象操作流--存储对象

1.什么是对象操作流
    * 该流可以将一个对象写出, 或者读取一个对象到程序中. 也就是执行了序列化和反序列化的操作.
* 2.使用方式
    * 写出: new ObjectOutputStream(OutputStream),     writeObject()

            public class Demo3_ObjectOutputStream {
    
                /**
                 * @param args
                 * @throws IOException 
                 * 将对象写出,序列化
                 */
                public static void main(String[] args) throws IOException {
                    Person p1 = new Person("张三", 23);
                    Person p2 = new Person("李四", 24);
            //        FileOutputStream fos = new FileOutputStream("e.txt");
            //        fos.write(p1);
            //        FileWriter fw = new FileWriter("e.txt");
            //        fw.write(p1);
                    //无论是字节输出流,还是字符输出流都不能直接写出对象
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));//创建对象输出流
                    oos.writeObject(p1);
                    oos.writeObject(p2);
                    oos.close();
                }
            
            }
_IO流(对象操作流ObjectInputStream)
* 读取: new ObjectInputStream(InputStream), readObject()
    * 
            public class Demo3_ObjectInputStream {

                /**
                 * @param args
                 * @throws IOException 
                 * @throws ClassNotFoundException 
                 * @throws FileNotFoundException 
                 * 读取对象,反序列化
                 */
                public static void main(String[] args) throws IOException, ClassNotFoundException {
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
                    Person p1 = (Person) ois.readObject();    ###########
                    Person p2 = (Person) ois.readObject();      ###########
                    System.out.println(p1);
                    System.out.println(p2);
                    ois.close();
                }
            
            }
    
IO流(对象操作流优化)
* 将对象存储在集合中写出

    Person p1 = new Person("张三", 23);
    Person p2 = new Person("李四", 24);
    Person p3 = new Person("马哥", 18);
    Person p4 = new Person("辉哥", 20);
    
    ArrayList<Person> list = new ArrayList<>();
    list.add(p1);
    list.add(p2);
    list.add(p3);
    list.add(p4);
    
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f.txt"));
    oos.writeObject(list);                                    //写出集合对象
    
    oos.close();
* 读取到的是一个集合对象

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("f.txt"));
            ArrayList<Person> list = (ArrayList<Person>)ois.readObject();    //泛型在运行期会被擦除,索引运行期相当于没有泛型
        //想去掉黄色可以加注解            
        @SuppressWarnings("unchecked")
            for (Person person : list) {
                System.out.println(person);
            }
        
        ois.close();

 

posted on 2019-08-06 23:36  妖碧落  阅读(379)  评论(0编辑  收藏  举报