Schema schema = new Schema.Parser().parse(new File(
"src/main/avro/dog.avsc"));
// Using this schema, let's create some users.
GenericRecord user1 = new GenericData.Record(schema);
user1.put("name", "Alyssa");
user1.put("favorite_number", 256);
// Leave favorite color null
GenericRecord user2 = new GenericData.Record(schema);
user2.put("name", "Ben");
user2.put("favorite_number", 7);
user2.put("favorite_color", "red");
System.out.println(user1);
System.out.println(user2);
// Serialize user1 and user2 to disk
String iString = new SimpleDateFormat("yyyyMMddHHmmssSSS")
.format(new Date());
File file = new File("C:\\Users\\need\\Desktop\\新建文件夹 (2)\\avro_file\\dog_" + iString + ".avro");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(
schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(
datumWriter);
dataFileWriter.create(schema, file);
dataFileWriter.append(user1);
dataFileWriter.append(user2);
dataFileWriter.close();
// Deserialize users from disk
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(
schema);
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(
file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext()) {
// Reuse user object by passing it to next(). This saves us from
// allocating and garbage collecting many objects for files with
// many items.
user = dataFileReader.next(user);
System.out.println(user);
}