hadoop深入研究:(十七)——Avro Datafile

來源:互聯網
上載者:User

轉載請寫明來源地址:http://blog.csdn.net/lastsweetop/article/details/9817999

所有源碼在github上,https://github.com/lastsweetop/styhadoop

datafile組成datafile的組成如:datafile分為檔案頭是資料區塊,如果看圖還是不明白,那麼看這個應該會很清楚,datafile檔案頭的schema:
{"type": "record", "name": "org.apache.avro.file.Header", "fields" : [   {"name": "magic", "type": {"type": "fixed", "name": "Magic", "size": 4}},   {"name": "meta", "type": {"type": "map", "values": "bytes"}},   {"name": "sync", "type": {"type": "fixed", "name": "Sync", "size": 16}},  ]}

資料區塊相對容易理解,這裡就不詳述了。要注意的是16位元組的同步標記,這個標記意味著datafile支援隨機讀,並且可以做分割,也意味著可以作為mapreduce的輸入

DataFileReader可以通過同步標記去隨機讀datafile檔案

voidseek(long position)Move to a specific, known synchronization point, one returned from DataFileWriter.sync() while writing.voidsync(long position)Move to the next synchronization point after a position.
datafile寫操作以代碼注釋的方式進行講解:
//首先建立一個副檔名為avro的檔案(副檔名隨意,這裡只是為了容易分辨)        File file = new File("data.avro");        //這行和前篇文章的代碼一致,建立一個Generic Record的datum寫入類        DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);        //和Encoder不同,DataFileWriter可以將avro資料寫入到檔案中        DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(writer);        //建立檔案,並且寫入頭資訊        dataFileWriter.create(schema,file);        //寫datum資料        dataFileWriter.append(datum);        dataFileWriter.append(datum);        dataFileWriter.close();
datafile讀操作以代碼注釋的方式進行講解

//這行也和前篇文章相同,Generic Record的datum讀取類,有點不一樣的就是這裡不需要再傳入schema,因為schema已經包含在datafile的頭資訊裡        DatumReader<GenericRecord> reader=new GenericDatumReader<GenericRecord>();        //datafile檔案的讀取類,指定檔案和datumreader        DataFileReader<GenericRecord> dataFileReader=new DataFileReader<GenericRecord>(file,reader);        //測試下讀寫的schema是否一致        Assert.assertEquals(schema,dataFileReader.getSchema());        //遍曆GenericRecord        for (GenericRecord record : dataFileReader){            System.out.println("left="+record.get("left")+",right="+record.get("right"));        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.