2015-04-28 78 views
0

從一個大的文件塊我有10K的實體(每行實體)閱讀在使用Java

我想在1K實體塊列出來讀取它的一個重要文件。

我曾嘗試:

public List<String> getNextRequestsChunk() { 
    List<String> requests = new ArrayList<>(); 
    try { 

     randomAccessFile.seek(currentSeekPosition); 

     String line = null; 
     while ((requests.size() < chunkSize) && (line = randomAccessFile.readLine()) != null) 
     { 
      currentSeekPosition += line.length(); 
      requests.add(line); 
     } 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     throw new RuntimeException(ex); 
    } 

    return requests; 
} 

我有這個文件:

11 
22 
33 
.. 
100100 

,當我重新運行該方法塊#2它不給我預期的字符串33但串2

chunkSize是2行,currentSeekPosition = 4)

我該如何解決這個問題?

+0

如果不是第10行,它會給你什麼? – ACV

+0

確保currentSeekPosition不在 – ACV

+0

之外的某個地方重置請參閱我的更新 –

回答

1

添加您的問題currentSeekPosition = randomAccessFile.getFilePointer();while

public List<String> getNextRequestsChunk() { 
    List<String> requests = new ArrayList<>(); 
    try { 

     randomAccessFile.seek(currentSeekPosition); 

     String line = null; 
     while ((requests.size() < chunkSize) && (line = randomAccessFile.readLine()) != null) 
     { 
      // currentSeekPosition += line.length()+1; 
      requests.add(line); 
     } 
     // add this 
     currentSeekPosition = randomAccessFile.getFilePointer(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     throw new RuntimeException(ex); 
    } 

    return requests; 
} 

readLine計算方式不會換行字符\n