栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Apache Avro反射

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Apache Avro反射

这是上述程序的有效版本。

这也对文件使用压缩。

import java.io.File;import org.apache.avro.Schema;import org.apache.avro.file.DataFileWriter;import org.apache.avro.file.DataFileReader;import org.apache.avro.file.CodecFactory;import org.apache.avro.io.DatumWriter;import org.apache.avro.io.DatumReader;import org.apache.avro.reflect.ReflectData;import org.apache.avro.reflect.ReflectDatumWriter;import org.apache.avro.reflect.ReflectDatumReader;import org.apache.avro.reflect.Nullable;public class Reflect {  public static class Packet {    int cost;    @Nullable TimeStamp stamp;    public Packet() {}  // required to read    public Packet(int cost, TimeStamp stamp){      this.cost = cost;      this.stamp = stamp;    }  }  public static class TimeStamp {    int hour = 0;    int second = 0;    public TimeStamp() {}          // required to read    public TimeStamp(int hour, int second){      this.hour = hour;      this.second = second;    }  }  public static void main(String[] args) throws Exception {    // one argument: a file name    File file = new File(args[0]);    // get the reflected schema for packets    Schema schema = ReflectData.get().getSchema(Packet.class);    // create a file of packets    DatumWriter<Packet> writer = new ReflectDatumWriter<Packet>(Packet.class);    DataFileWriter<Packet> out = new DataFileWriter<Packet>(writer)      .setCodec(CodecFactory.deflateCodec(9))      .create(schema, file);    // write 100 packets to the file, odds with null timestamp    for (int i = 0; i < 100; i++) {      out.append(new Packet(i, (i%2==0) ? new TimeStamp(12, i) : null));    }    // close the output file    out.close();    // open a file of packets    DatumReader<Packet> reader = new ReflectDatumReader<Packet>(Packet.class);    DataFileReader<Packet> in = new DataFileReader<Packet>(file, reader);    // read 100 packets from the file & print them as JSON    for (Packet packet : in) {      System.out.println(ReflectData.get().toString(packet));    }    // close the input file    in.close();  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号