標籤:system cep 序列化 new [] java序列化 except temp port
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());
/*
* 輸出結果:
* Apple001China
*/
}
}
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;
}
}
2018-07-25期 Java序列化和還原序列化編程小案例