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]

  • 相关阅读:
    poj 3666 Making the Grade
    poj 3186 Treats for the Cows (区间dp)
    hdu 1074 Doing Homework(状压)
    CodeForces 489C Given Length and Sum of Digits...
    CodeForces 163A Substring and Subsequence
    CodeForces 366C Dima and Salad
    CodeForces 180C Letter
    CodeForces
    hdu 2859 Phalanx
    socket接收大数据流
  • 原文地址:https://www.cnblogs.com/pwc1996/p/5957870.html
Copyright © 2011-2022 走看看