Person 類, 序列化後就表明對象能夠做爲二進制的數據流進行傳輸
package com.qunar.basicJava.javase.io.serializable;
import java.io.Serializable;
/**
* Author: libin.chen@qunar.com Date: 14-6-6 10:21
*/
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名 : " + this.name + "; 年齡 : " + this.age;
}
}
ObjectOutputStream 將序列化後的對象寫入到文件中
package com.qunar.basicJava.javase.io.serializable;
import java.io.*;
/**
* Author: libin.chen@qunar.com Date: 14-6-6 10:25
*/
public class SerDemo01 {
public static void main(String[] args) throws IOException {
File file = new File("/home/hp/tmp/test.txt");
ObjectOutputStream objectOutputStream = null;
OutputStream outputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(new Person("張三", 30));
outputStream.close();
}
}
ObjectInputStream 將序列化的對象傳回來
package com.qunar.basicJava.javase.io.serializable;
import java.io.*;
/**
* Author: libin.chen@qunar.com Date: 14-6-6 10:27
*/
public class SerDemo02 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file = new File("/home/hp/tmp/test.txt");
ObjectInputStream objectInputStream = null;
InputStream inputStream = new FileInputStream(file);
objectInputStream = new ObjectInputStream(inputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
System.out.println(object);
}
}