您的位置:首页 > 编程语言 > Java开发

JAVA | 50 - IO 高级应用 | 对象序列化

2017-12-04 21:26 537 查看
对象序列化就是将保存在内存中的对象数据转换为二进制数据流进行传输的操作。

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

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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐