对象序列化到磁盘这个问题听说过,但是从来没有用过,通过它核心只是为了认知序列化。
ObjectInputStream和ObjectOutputStream可以用以读写序列化的对象。
DataInputStream和DataOutputStream可以实现基础数据类型和字符串数据的读写,而ObjectInputStream和ObjectOutputStream在此基础上还可以对对象进行读写操作。
public class ObjectInputStream
extends InputStream
implements ObjectInput, ObjectStreamConstantsObjectInputStream反序列化先前使用ObjectOutputStream编写的原始数据和对象。
ObjectOutputStream和ObjectInputStream可以分别为与FileOutputStream和FileInputStream一起使用的对象图提供持久性存储的应用程序。 ObjectInputStream用于恢复先前序列化的对象。 其他用途包括使用套接字流在主机之间传递对象,或者在远程通信系统中进行封送和解组参数和参数。
ObjectInputStream确保从流中创建的图中的所有对象的类型与Java虚拟机中存在的类匹配。 根据需要使用标准机制加载类。
只能从流中读取支持java.io.Serializable或java.io.Externalizable接口的对象
public static void main(String[] args) throws IOException, ClassNotFoundException {
try (
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("d:\\object.data"));
) {
outputStream.writeUTF("火男");
outputStream.writeDouble(11558.72);
outputStream.writeObject(new Date());
}
try (
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("d:\\object.data"))
) {
String name = inputStream.readUTF();
Double salary = inputStream.readDouble();
Date date = (Date) inputStream.readObject();
System.out.println(name + "在" + date + "发了" + salary + "工资");
}
}
火男在Sun Jan 19 15:50:15 CST 2020发了11558.72工资
Serializable接口
public interface Serializable {
}
看下源码很强大,一百多行注释,除了接口定义内部没有一行代码,它只是一个定义,一个标准,具体可以阅读这个接口的注释。
大多常见的数据类型都实现了这个接口,如果对没有实现这个接口的对象进行序列化就会触发NotSerializableException异常。
对象序列化不存储对象静态变量的值
另外如果一个对象有些实例数据域不能序列化,怎么办?
加上关键字transient,就可以忽略这个实例域。
序列化数组
如果数组中的所有元素都是可序列化的,那么这个数组就是可序列化的。
public static void main(String[] args) throws IOException, ClassNotFoundException {
int[] numbers = {1, 2, 3};
String[] strings = {"妲己", "剑侠客", "小苍"};
try (
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("d:\\object.data"));
) {
outputStream.writeObject(numbers);
outputStream.writeObject(strings);
}
try (
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("d:\\object.data"))
) {
numbers = (int[]) inputStream.readObject();
strings = (String[]) inputStream.readObject();
for (int i : numbers
) {
System.out.print(i + "\t");
}
System.out.println();
for (String str : strings
) {
System.out.print(str + "\t");
}
}
}