java avro串行化反串行化 方法2 无需使用 avro_tools.jar工具包

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);
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值