【问题标题】:reading in chunks from a big file using java使用java从大文件中读取块
【发布时间】:2015-07-07 19:10:59
【问题描述】:

我有一个包含 10K 实体的大文件(每行实体)

我想以 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

当我为 chunk#2 重新运行此方法时,它没有给我预期的字符串 33,而是字符串 2

chunkSize 是 2 行,currentSeekPosition = 4)

我该如何解决这个问题?

【问题讨论】:

  • 如果不是第 10 行,它会给你什么?
  • 确保 currentSeekPosition 未在外部某处重置
  • 请看我的更新
  • 我觉得你需要加上:currentSeekPosition += line.length() + 1;
  • 你为什么还要乱用 seek()?只需读取数据并让文件指针自动前进。

标签: java file file-io io randomaccessfile


【解决方案1】:

while循环之后添加currentSeekPosition = randomAccessFile.getFilePointer();

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

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2012-01-05
    • 1970-01-01
    • 2011-01-22
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多