Java - How to quickly read a large number of data binary file

在此將說明若我們產生一大量資料的binary file,如何透過set offset position來快速讀去指定區段的資料,如此一來就可以取代透過迴圈來走訪不需要的區段!

此binary file format可以參考如何輸出及讀取binary file,在此就不再贅述!

首先是輸出大量資料的binary file,在此修改如何輸出及讀取binary file writeBinaryFile method輸出資料的程式區塊,如下:
  1. int count = 1000000;
  2. ...
  3. int threshold = count / 5;
  4. int currIndex = -1;
  5. int value = 0;
  6. int index = 0;
  7. for(int i = 0 ; i < count ; i++) {
  8. index = i / threshold;
  9. value = (index + 1) * 10;
  10. ostream.writeInt(value);
  11. if(index != currIndex) {
  12. currIndex = index;
  13. ostream.flush();
  14. }
  15. }

主要是針對write Integer data的部分進行資料追加,本來是輸出10筆亂數資料,在此將輸出100萬筆資料,並設定每20萬筆為一區間,每個區間輸出相同的數字,分別是10, 20,.., 50等等!


再來是讀取binary file的部分,在此同樣修改如何輸出及讀取binary file readBinaryFile method讀取資料的程式區塊,如下:
  1. long currentTime = System.currentTimeMillis();
  2. int value = 0;
  3. int currVal = 0;
  4. count = count - 800000;
  5. istream.skipBytes(800000 * 4);//Integer -> 4 bytes
  6. for(int i = 0 ; i < count ; i++) {
  7. value = istream.readInt();
  8. if(value != currVal) {
  9. currVal = value;
  10. System.out.println(currVal+", "+i);
  11. }
  12. }
  13. long diff = System.currentTimeMillis() - currentTime;
  14. System.out.println(diff);

在此計算讀取時間,本來整個讀完100萬筆資料需要將近14秒多的時間,而透過skipBytes針對目前offset position要skip多少byte,在此是要去讀第80筆後的資料,因此需skip 800000 * 4 bytes,如此一來offset position會指到最後一個區段的start,也就是80萬到100萬之間。因此讀出來的第一筆資料就會是這個區間的數字為50! 而整體的時間也只剩下2.824秒左右!

印出來的console如下:
readBinaryFile...
START
50, 0
2824
END

留言