序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
- 以String为例测试
package mytest;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class ObjectOutputStreamTest {
public static void main(String[] args) {
ObjectOutputStream oos = null;try {
oos = new ObjectOutputStream(new FileOutputStream("object.data"));oos.writeObject(new String("这是一个测试!"));} catch (IOException e) {
e.printStackTrace();} finally {
try {
oos.close();} catch (IOException e) {
e.printStackTrace();}}}}
package mytest;import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;public class ObjectInputStreamTest {
public static void main(String[] args) {
ObjectInputStream ois = null;try {
ois = new ObjectInputStream(new FileInputStream("object.data"));Object obj = ois.readObject();String str = (String)obj;System.out.println(str);} catch (IOException e) {
e.printStackTrace();} catch (ClassNotFoundException e) {
e.printStackTrace();} finally {
try {
ois.close();} catch (IOException e) {
e.printStackTrace();}}}}
-
自定义类person测试
2.1 自定义类序列化需要实现接口:Serializable
2.2 提供一个全局常量:serialVersionUID
package mytest;import java.io.Serializable;public class Person implements Serializable {
private static final long serialVersionUID = 537106506708875853L;private String name;private int age;public Person() {
}public Person(String name, int age) {
this.name = name;this.age = age;}public String getName() {
return name;}public void setName(String name) {
this.name = name;}public int getAge() {
return age;}public void setAge(int age) {
this.age = age;}@Overridepublic String toString() {
return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}
package mytest;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class ObjectOutputStreamTest2 {
public static void main(String[] args) {
ObjectOutputStream oos = null;try {
oos = new ObjectOutputStream(new FileOutputStream("object.data"));oos.writeObject(new Person("张三",30));} catch (IOException e) {
e.printStackTrace();} finally {
try {
oos.close();} catch (IOException e) {
e.printStackTrace();}}}}
package mytest;import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;public class ObjectInputStreamTest2 {
public static void main(String[] args) {
ObjectInputStream ois = null;try {
ois = new ObjectInputStream(new FileInputStream("object.data"));Object obj = ois.readObject();Person p = (Person) obj;System.out.println(p);} catch (IOException e) {
e.printStackTrace();} catch (ClassNotFoundException e) {
e.printStackTrace();} finally {
try {
ois.close();} catch (IOException e) {
e.printStackTrace();}}}
}