ObjectOutputStream类与ObjectInputStream类

OutputStream与InputStream子类

public class ObjectStream {
    static String file="e:\\fileOut.txt";
    public static void main(String[] args) {
        // TODO Auto-generated method stub

//      重点:必须要有类的class文件
//      重点:该类实现Serializable接口,标记型接口
//      ObjectOutputStream.writeObject(person);
//      ObjectInputStream.readObject();
//      重点:类的静态变量无法序列化
//      由于静态变量不属于对象
//      transient修饰成员变量。阻止其序列化。
        func();
        func2();
    }

    private static void func() {
        // TODO Auto-generated method stub
        FileOutputStream fileOutputStream=null;
        ObjectOutputStream objectOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream(file);
            objectOutputStream=new ObjectOutputStream(fileOutputStream);
//          创建所需的对象类
            Person person=new Person("老大",1);
//          写对象
            objectOutputStream.writeObject(person);
        } catch (IOException e) {
            // TODO: handle exception
        } finally {
            try {
                if (objectOutputStream!=null)
                    objectOutputStream.close();
                if (fileOutputStream!=null)
                    fileOutputStream.close();
            } catch (IOException e2) {
                // TODO: handle exception
            }
        }
    }

    private static void func2() {
        // TODO Auto-generated method stub
        FileInputStream fileInputStream=null;
//      创建反序列化流
        ObjectInputStream objectInputStream=null;
        try {
            fileInputStream=new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);
//          调用方法读取对象
            Object object=objectInputStream.readObject();
            System.out.println(object.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (objectInputStream!=null) 
                    objectInputStream.close();
                if (fileInputStream!=null)
                    fileInputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Person类:

public class Person implements Serializable {
    private String name;
    private int age;
    
    public Person(String string, int i) {
        // TODO Auto-generated constructor stub
        this.name=name;
        this.age=age;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容