对象的序列化

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。对象的序列化,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

使用文件完成对象的存储和取出

	    //对象输出流
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new FileOutputStream(
                        new File("D:\\BaiduNetdiskDownload\\dailyLearning\\data.obj")));
        objectOutputStream.writeObject(new Person(12,"llm"));
        objectOutputStream.close();

        //对象输入流
        ObjectInputStream objectInputStream = new ObjectInputStream(
                new FileInputStream(
                        new File("D:\\BaiduNetdiskDownload\\dailyLearning\\data.obj")));
        Person o = (Person)objectInputStream.readObject();
        System.out.println(o);
        objectInputStream.close();

使用序列化的方式完成对象的深度拷贝

class CloneUtil {

    //对象序列化实现对象的clone()
    //先把对象序列化成字节流,然后再把字节流反序列化成对象
    //@SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) throws CloneNotSupportedException {
        T t2 = null;
        try {
            //使用字节输入流完成对象序列化
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.close();
            //把序列化的数据反序列化回去,完成clone
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            t2 = (T) objectInputStream.readObject();
            objectInputStream.close();
            return t2;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t2;
    }
}

测试类

public static void main(String[] args) throws Exception {
        Person llm = new Person(12, "llm");
        Person clone = CloneUtil.clone(llm);
        System.out.println(llm+"/-/ "+clone);
        System.out.println(llm == clone);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/202518.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!