下面将实现一个序列化对象的例子,也就是将对象保存到文件中,在从文件中读出对象
步骤:
1确保要保存的对象实现了Serializeable 接口
2通过创建一个ObjectOutputStream()对象来打开文件
3通过writeObject()将对象写入文件
4完成后关闭输入流。
从文件中读取对象
1通过一个ObjectInputStream()对象来打开文件
2通过调用readObject()来读取对象,并将对像强制转换为读取对象的实际类型
3关闭流。
一:定义一个类My.class 作为序列化的对象
/**
*
*/
package hust.ophoneclub.SerialDemo;
import java.io.File;
import java.io.Serializable;
/**
* @author chenhao
*
*/
public class MyClass implements Serializable {
String str;
double[] vals;
File file;
public MyClass(String str, double[] numbers, String fileName){
this.str = str;
vals = numbers;
file = new File(fileName);
}
public String toString(){
String data = " str:" + str + "\n" + "vlas ";
for(double d: vals) {
data += d + " ";
}
data += "\nfile name " + file.getName();
return data;
}
}
定义一个类来实现这个序列化的过程
/**
*
*/
package hust.ophoneclub.SerialDemo;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author chenhao
*
*/
public class SerialDemo {
public static void main(String args[] ){
saveObj();
readObj();
//
}
/**
*
*/
private static void saveObj() {
double v1[] = {1.1, 2.2, 3.3};
double v2[] = {1.2, 2.3, 3.4};
MyClass object1 = new MyClass("first obj", v1, "firstObj.txt");
MyClass object2 = new MyClass("first obj", v2, "secondObj.txt");
//open the output file
ObjectOutputStream out;
try {
out = new ObjectOutputStream(new FileOutputStream("obj.dat"));
} catch (Exception e) {
printError(e);
return;
}
//write the obj to the file
try {
writeObjToFile(object1, out);
writeObjToFile(object2, out);
} catch (Exception e) {
printError(e);
}
try{
out.close();
}catch (Exception e) {
printError(e);
}
}
/**
* @param e
*/
private static void printError(Exception e) {
System.out.println(e.getMessage());
}
/**
*
*/
private static void readObj() {
//read the object from the file
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("obj.dat"));
} catch (Exception e) {
printError(e);
return;
}
System.out.println("\nreading obj from the file ");
try {
MyClass inputObj;
inputObj = (MyClass)in.readObject();
System.out.println("First Objetct" + inputObj);
inputObj = (MyClass)in.readObject();
System.out.println("second Objetct" + inputObj);
} catch (Exception e) {
printError(e);
}
try {
in.close();
} catch (Exception e) {
printError(e);
}
}
/**
* @param object1
* @param out
* @throws IOException
*/
private static void writeObjToFile(MyClass object1, ObjectOutputStream out)
throws IOException {
System.out.println("write the obj to the file");
System.out.println(object1);
out.writeObject(object1);
}
}
输出的结果
write the obj to the file
str:first obj
vlas 1.1 2.2 3.3
file name firstObj.txt
write the obj to the file
str:first obj
vlas 1.2 2.3 3.4
file name secondObj.txt
reading obj from the file
First Objetct str:first obj
vlas 1.1 2.2 3.3
file name firstObj.txt
second Objetct str:first obj
vlas 1.2 2.3 3.4
file name secondObj.txt