为了账号安全,请及时绑定邮箱和手机立即绑定

如何反序列化avro文件

如何反序列化avro文件

梦里花落0921 2022-05-20 18:39:43
我想阅读一个 hdfs 文件夹,其中包含带有 spark 的 avro 文件。然后我想反序列化这些文件中包含的 avro 事件。我想在没有 com.databrics 库(或任何其他允许轻松完成的库)的情况下做到这一点。问题是我在反序列化方面遇到了困难。我假设我的 avro 文件是用 snappy 压缩的,因为在文件的开头(就在模式之后),我有avro.codecsnappy书面。然后是可读或不可读的字符。我第一次尝试反序列化 avro 事件如下:public static String deserialize(String message) throws IOException {    Schema.Parser schemaParser = new Schema.Parser();    Schema avroSchema = schemaParser.parse(defaultFlumeAvroSchema);    DatumReader<GenericRecord> specificDatumReader = new SpecificDatumReader<GenericRecord>(avroSchema);        byte[] messageBytes = message.getBytes();    Decoder decoder = DecoderFactory.get().binaryDecoder(messageBytes, null);    GenericRecord genericRecord = specificDatumReader.read(null, decoder);    return genericRecord.toString();}当我想反序列化一个没有 avro.codecsbappy 的 avro 文件时,此函数有效。在这种情况下,我有错误:格式错误的数据:长度为负数:-50所以我尝试了另一种方法,即:    private static void deserialize2(String path) throws IOException {    DatumReader<GenericRecord> reader = new GenericDatumReader<>();    DataFileReader<GenericRecord> fileReader =            new DataFileReader<>(new File(path), reader);    System.out.println(fileReader.getSchema().toString());    GenericRecord record = new GenericData.Record(fileReader.getSchema());    int numEvents = 0;    while (fileReader.hasNext()) {        fileReader.next(record);        ByteBuffer body = (ByteBuffer) record.get("body");        CharsetDecoder decoder = Charsets.UTF_8.newDecoder();        System.out.println("Positon of the index " + body.position());        System.out.println("Size of the array : " + body.array().length);        String bodyStr = decoder.decode(body).toString();        System.out.println("THE BODY STRING  ---> " bodyStr);        numEvents++;    }    fileReader.close();}它返回以下输出:索引 0 的位置数组大小:127482身体字符串--->我可以看到数组不是空的,但它只是返回一个空字符串。我该如何进行?
查看完整描述

2 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

转换为字符串时使用它:


String bodyStr = new String(body.array());

System.out.println("THE BODY STRING  ---> " + bodyStr);

来源:https ://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/


查看完整回答
反对 回复 2022-05-20
?
冉冉说

TA贡献1877条经验 获得超1个赞

好吧,看来你的路不错。但是,您ByteBuffer可能没有合适的byte[]数组来解码,所以让我们尝试以下方法:


byte[] bytes = new byte[body.remaining()];

buffer.get(bytes);

String result = new String(bytes, "UTF-8"); // Maybe you need to change charset

这应该可行,您已经在ByteBuffer包含实际数据的问题中显示,如代码示例中给出的,您可能必须更改字符集。


字符集列表:https ://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html


也很有用:https ://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html


查看完整回答
反对 回复 2022-05-20
  • 2 回答
  • 0 关注
  • 272 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号