JAVA | 50

来源:互联网 发布:linux sip服务器 编辑:程序博客网 时间:2024/05/01 20:03

对象序列化就是将保存在内存中的对象数据转换为二进制数据流进行传输的操作。

不是所有的类都需要被序列化,只有需要传输的对象所在的类才需要被序列化。

import java.io.*;class Book implements Serializable{ // 该类可以实现对象序列化    private transient String title; // 此属性不可以被序列化    private int price;    public Book(String title, int price){        this.title = title;        this.price = price;    }    @Override    public String toString() {        return this.title + " " + this.price;    }}public class Main {    public static void main(String[] args) throws Exception{        Book book = new Book("java",100);        ser(book);        dser();    }    public static void ser(Book book) throws Exception{        File file = new File("/Users/yuzhen/File/testA.txt");        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));        objectOutputStream.writeObject(book);        objectOutputStream.close();    }    public static void dser() throws Exception{        File file = new File("/Users/yuzhen/File/testA.txt");        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));        Object object = objectInputStream.readObject();        System.out.println((Book)object);    }}
原创粉丝点击