- 利用ObjectOutputStream类进行对象序列化,ObjectInputStream类进行对象反序列化。
- 实现序列化的对象必须实现Serializable接口,提供全局常量serialVersionUID,而且其所有属性也是可序列化的。
- 利用对象序列化可以快速地对一个对象进行深拷贝。
import java.io.*;
public class SerializableTest {
public static void main(String[] args) {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream("D:\\Desktop\\Files\\Object.dat", true));
outputStream.writeObject(new Test1("Test1", 1, new Test2("Test2", 2)));
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream("D:\\Desktop\\Files\\Object.dat"));
Test1 test1 = (Test1) inputStream.readObject();
System.out.println(test1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
Test1 test1 = new Test1("Test1", 10, new Test2("Test2", 20));
ByteArrayOutputStream data = new ByteArrayOutputStream();
outputStream = new ObjectOutputStream(data);
outputStream.writeObject(test1);
inputStream = new ObjectInputStream(new ByteArrayInputStream(data.toByteArray()));
Test1 test2 = (Test1) inputStream.readObject();
System.out.println(test1);
System.out.println(test2);
System.out.println(test1 == test2);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class Test1 implements Serializable {
private static final long serialVersionUID = -7300046014501169240L;
private String str;
private int value;
private Test2 test2;
public Test1(String str, int value, Test2 test2) {
this.str = str;
this.value = value;
this.test2 = test2;
}
@Override
public String toString() {
return "Test1{" +
"str='" + str + '\'' +
", value=" + value +
", test2=" + test2 +
'}';
}
}
class Test2 implements Serializable {
private static final long serialVersionUID = 3341032494948326316L;
private String str;
private int value;
public Test2(String str, int value) {
this.str = str;
this.value = value;
}
@Override
public String toString() {
return "Test2{" +
"str='" + str + '\'' +
", value=" + value +
'}';
}
}