2018-07-25期 Java序列化和反序列化编程小案例

package cn.sjq.Serializable.java;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStream;

/**

* 将Fruit对象写入文件

* @author songjq

*

*/

public class JavaSerializableDemo {

public static void main(String[] args) throws Exception {

//定义水果对象

Fruit f = new Fruit();

f.setName("Apple");

f.setType("001");

f.setProduction("China");

/*

* 将水果对象f写入文件(Fruit未实现序列化)

*/

//定义输出流

OutputStream out = new FileOutputStream("d:\\temp\\Fruit.ser");

//定义对象输出流

ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);

objectOutputStream.writeObject(f);

//关闭流

out.close();

objectOutputStream.close();

/**

* 测试结论:

* 1、Fruit未实现序列化

* Exception in thread "main" java.io.NotSerializableException: cn.sjq.Serializable.java.Fruit

* 说明如果一个对象要被写入文件,需要对该对象进行序列化

* 2、Fruit实现序列化 public class Fruit implements Serializable

* 对象Fruit成功写入了文件d:\\temp\\Fruit.ser

*/

/**

* 反序列化,将Fruit.ser反序列化成Fruit对象输出控制台

*/

InputStream in = new FileInputStream("d:\\temp\\Fruit.ser");

ObjectInputStream objectInputStream = new ObjectInputStream(in);

Fruit fruit = (Fruit) objectInputStream.readObject();

System.out.println(f.getName()+"\t"+f.getType()+"\t"+f.getProduction());

/*

* 输出结果:

* Apple 001 China

*/

}

}

package cn.sjq.Serializable.java;

import java.io.Serializable;

/**

* Java序列化:如果一个类实现了Java序列化,这个类就可以作为输入输出对象

* 定义一个JAVA Bean Fruit

* @author songjq

*

*/

public class Fruit implements Serializable {

private String name;

private String type;

private String production;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getProduction() {

return production;

}

public void setProduction(String production) {

this.production = production;

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章