Avro 简明教程
AVRO - Deserialization By Generating Class
如前所述,可以通过生成与模式相对应的类或通过使用解析器库来读取 Avro 模式到一个程序中。本章介绍了如何使用 Avro 读取模式 by generating a class 和 Deserialize 数据。
As described earlier, one can read an Avro schema into a program either by generating a class corresponding to the schema or by using the parsers library. This chapter describes how to read the schema by generating a class and Deserialize the data using Avro.
Deserialization by Generating a Class
序列化数据存储在文件 emp.avro 中。你可以使用 Avro 序列化并读取它。
The serialized data is stored in the file emp.avro. You can deserialize and read it using Avro.

按照以下步骤从文件中序列化序列化数据。
Follow the procedure given below to deserialize the serialized data from a file.
Step 1
使用 SpecificDatumReader 类创建一个 DatumReader 接口对象。
Create an object of DatumReader interface using SpecificDatumReader class.
DatumReader<emp>empDatumReader = new SpecificDatumReader<emp>(emp.class);
Step 2
为 emp 类实例化 DataFileReader 。此类从文件中读取序列化数据。它将 Dataumeader 对象和序列化数据所在的文件夹路径作为构造函数的参数。
Instantiate DataFileReader for emp class. This class reads serialized data from a file. It requires the Dataumeader object, and path of the file where the serialized data is existing, as a parameters to the constructor.
DataFileReader<emp> dataFileReader = new DataFileReader(new File("/path/to/emp.avro"), empDatumReader);
Step 3
使用 DataFileReader 的方法打印序列化数据。
Print the deserialized data, using the methods of DataFileReader.
-
The hasNext() method will return a boolean if there are any elements in the Reader.
-
The next() method of DataFileReader returns the data in the Reader.
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
Example – Deserialization by Generating a Class
以下完整程序展示了如何使用 Avro 序列化文件中的数据。
The following complete program shows how to deserialize the data in a file using Avro.
import java.io.File;
import java.io.IOException;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.io.DatumReader;
import org.apache.avro.specific.SpecificDatumReader;
public class Deserialize {
public static void main(String args[]) throws IOException{
//DeSerializing the objects
DatumReader<emp> empDatumReader = new SpecificDatumReader<emp>(emp.class);
//Instantiating DataFileReader
DataFileReader<emp> dataFileReader = new DataFileReader<emp>(new
File("/home/Hadoop/Avro_Work/with_code_genfile/emp.avro"), empDatumReader);
emp em=null;
while(dataFileReader.hasNext()){
em=dataFileReader.next(em);
System.out.println(em);
}
}
}
浏览到生成代码所在目录。在本例中,在 home/Hadoop/Avro_work/with_code_gen. 。
Browse into the directory where the generated code is placed. In this case, at home/Hadoop/Avro_work/with_code_gen.
$ cd home/Hadoop/Avro_work/with_code_gen/
现在,复制并保存以上程序到名为 DeSerialize.java 的文件中。如下所示,对其进行编译和执行:
Now, copy and save the above program in the file named DeSerialize.java. Compile and execute it as shown below −
$ javac Deserialize.java
$ java Deserialize