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