本文共 2488 字,大约阅读时间需要 8 分钟。
ObjectInputStream in Java can be used to convert InputStream to object. The process of converting the input stream to an object is called deserialization. In last post, we learned about and converted java object to output stream and write to file. Here we will read the same serialized file to create an object in java.
Java中的ObjectInputStream可用于将InputStream转换为对象。 将输入流转换为对象的过程称为反序列化。 在上一篇文章中,我们了解了并将Java对象转换为输出流并写入文件。 在这里,我们将读取相同的序列化文件以在Java中创建一个对象。
ObjectInputStream is part of classes. It’s purpose is to provide us a way to convert input stream to object in java program. ObjectInputStream constructor take InputStream as argument. Since we are reading serialized object from file, we will be using FileInputStream with our ObjectInputStream to read object from file.
ObjectInputStream是类的一部分。 目的是为我们提供一种在Java程序中将输入流转换为对象的方法。 ObjectInputStream构造函数将InputStream作为参数。 由于我们正在从文件读取序列化的对象,因此我们将使用FileInputStream和ObjectInputStream来从文件读取对象。
java.io.ObjectInputStream
readObject()
is used to read input stream to Object. We have to do class casting to convert Object to actual class. Below is the ObjectInputStream example program to read object from file.
java.io.ObjectInputStream
readObject()
用于将输入流读取到Object。 我们必须进行类转换以将Object转换为实际类。 下面是ObjectInputStream示例程序,用于从文件读取对象。
package com.journaldev.files;import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;public class ObjectInputStreamExample { public static void main(String[] args) { try { FileInputStream is = new FileInputStream("EmployeeObject.ser"); ObjectInputStream ois = new ObjectInputStream(is); Employee emp = (Employee) ois.readObject(); ois.close(); is.close(); System.out.println(emp.toString()); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } }}
Below image shows the output produced by the above program.
下图显示了以上程序产生的输出。
There is a lot more to serialization and deserialization in java. For example, what happens if we change the java class before deserialization. What is the use of serialVersionUID
? What happens to serialization with inheritance where superclass doesn’t implement the Serializable interface? I have tried to answer these into a detailed post, please read .
Java中的序列化和反序列化还有很多。 例如,如果我们在反序列化之前更改java类会发生什么。 serialVersionUID
的用途是什么? 在超类未实现Serializable接口的情况下,带有继承的序列化会发生什么? 我已尝试在详细的帖子中回答这些问题,请阅读 。
Reference:
参考:
翻译自:
转载地址:http://zuqzd.baihongyu.com/