Debian Codegraph @

doc/examples/java-example/src/main/java/example/GenericMain.java

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package example;
20
21 import java.io.File;
22 import java.io.IOException;
23
24 import org.apache.avro.Schema;
25 import org.apache.avro.Schema.Parser;
26 import org.apache.avro.file.DataFileReader;
27 import org.apache.avro.file.DataFileWriter;
28 import org.apache.avro.generic.GenericData;
29 import org.apache.avro.generic.GenericDatumReader;
30 import org.apache.avro.generic.GenericDatumWriter;
31 import org.apache.avro.generic.GenericRecord;
32 import org.apache.avro.io.DatumReader;
33 import org.apache.avro.io.DatumWriter;
34
35 public class GenericMain {
36 public static void main(String[] args) throws IOException {
37 Schema schema = new Parser().parse(new File("./../user.avsc"));
38
39 GenericRecord user1 = new GenericData.Record(schema);
40 user1.put("name", "Alyssa");
41 user1.put("favorite_number", 256);
42 // Leave favorite color null
43
44 GenericRecord user2 = new GenericData.Record(schema);
45 user2.put("name", "Ben");
46 user2.put("favorite_number", 7);
47 user2.put("favorite_color", "red");
48
49 // Serialize user1 and user2 to disk
50 File file = new File("users.avro");
51 DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
52 DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
53 dataFileWriter.create(schema, file);
54 dataFileWriter.append(user1);
55 dataFileWriter.append(user2);
56 dataFileWriter.close();
57
58 // Deserialize users from disk
59 DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
60 GenericRecord user = null;
61 try(DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader)){
62 while (dataFileReader.hasNext()) {
63 // Reuse user object by passing it to next(). This saves us from
64 // allocating and garbage collecting many objects for files with
65 // many items.
66 user = dataFileReader.next(user);
67 System.out.println(user);
68 }
69 }
70
71
72 }
73 }