JavaSE---对象序列化

1、对象序列化机制  允许把内存中的Java对象转换成平台无关的二进制流,从而可以将二进制流持久保存到磁盘  或  在网络中直接传输;

            (目的:使得对象可以脱离程序的运行而独立存在)

package com.an.serialize;

import java.io.Serializable;

public class Person implements Serializable {

    private String name;
    private int age;

    public Person(){

    }

    public Person(String name,int age){
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

package com.an.serialize;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Test {

    public static void main(String[] args){
        ObjectOutputStream objectOutputStream=null;
        try {
            objectOutputStream=new ObjectOutputStream(new FileOutputStream("a.txt"));
            objectOutputStream.writeObject(new Person("jack",22));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (objectOutputStream!=null){
                    objectOutputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

 

 

2、反序列化  :从二进制流中恢复Java对象

package com.an.serialize;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeTest {

    public static void main(String[] args){
        ObjectInputStream objectInputStream=null;
        try {
            objectInputStream=new ObjectInputStream(new FileInputStream("a.txt"));
            Person person=(Person) objectInputStream.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (objectInputStream!=null){
                    objectInputStream.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
    }
}

 

    

猜你喜欢

转载自www.cnblogs.com/anpeiyong/p/10373112.html
0条评论
添加一条新回复