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]

  • 相关阅读:
    .net 文件夹是否存在的判断
    Lock Statement And Thread Synchronization
    如何利用EnteLib Unity Interception Extension 和PIAB实现Transaction
    OSQL 命令行工具
    How to build tab sets whitch headers display at bottom in WPF?
    Monitoring Clipboard Activity in C#
    产品经理讲座的感悟
    图说
    解决技术问题的9点建议
    为啥要整理需求?
  • 原文地址:https://www.cnblogs.com/pwc1996/p/5957870.html
Copyright © 2011-2022 走看看