zoukankan      html  css  js  c++  java
  • Java序列化和反序列化

    简介


    序列化是将实例化对象转换成字节数组,反序列化是将字节数组转换成对象。

    实例


    前提

    使需要序列化的类实现Serializable接口

    public class MyMessage implements Serializable

    序列化

        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        byte[] buffer=byteArrayOutputStream.toByteArray();
        objectOutputStream.close();
        byteArrayOutputStream.close();

    反序列化

        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);
        ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
        Object object=objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();

    测试类源码

    public class Test {
        public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException {
    
            MyMessage message=new MyMessage("123","456","Hello",new Date());
            File file=new File("F://temp");
            FileOutputStream outputStream=new FileOutputStream(file);
            ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(message);
            outputStream.write(byteArrayOutputStream.toByteArray());
            objectOutputStream.close();
            byteArrayOutputStream.close();
            outputStream.close();
            System.out.println("OK!");
    
    
            File file2=new File("F://temp");
            FileInputStream inputStream=new FileInputStream(file);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(buffer);
            ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
            MyMessage message2=(MyMessage) objectInputStream.readObject();
            System.out.println(message2.toString());
            objectInputStream.close();
            byteArrayInputStream.close();
            inputStream.close();
        }
    }
    

    测试结果为:
    OK!
    MyMessage [fromIp=123, toIp=456, text=Hello, image=null, date=Wed Sep 30 15:34:45 CST 2015]

  • 相关阅读:
    能够免费做商业站点的CMS讨论
    ntoskrnl.exe损坏或丢失的解决方式
    QT 仓库管理系统 开放源代码
    Disposable microfluidic devices: fabrication, function, and application Gina S. Fiorini and Daniel T
    DllImport中的EntryPoint
    IOS Table中Cell的重用reuse机制分析
    双slave的server_uuid同样问题
    怎样使用SetTimer MFC 够具体
    2013 成都邀请赛
    设计模式六大原则(2):里氏替换原则
  • 原文地址:https://www.cnblogs.com/pwc1996/p/5957870.html
Copyright © 2011-2022 走看看