亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何反序列化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 的位置數組大?。?27482身體字符串--->我可以看到數組不是空的,但它只是返回一個空字符串。我該如何進行?
查看完整描述

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 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號