java - 使用java从大文件中读取 block

标签 java file file-io io randomaccessfile

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

我想以 1K 实体 block 的形式读取它并列出。

我已经尝试过:

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)

我该如何解决这个问题?

最佳答案

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

关于java - 使用java从大文件中读取 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29927814/

相关文章:

java - 创建一个实现一些自己的方法的接口(interface)

windows - 自动将文件从 Linux 机器复制到 Windows 机器

asynchronous - Flutter:如何在不阻塞 UI 的情况下异步地从 Assets 中读取文件

从文件中读取的 C++ 反向波兰表示法

c# - 如何制作 "Read only"文件?

c++ - 为什么用 C 复制文件比 C++ 快得多?

vim - 如何设置打开文件时默认展开?

java - Spring Framework 中的 NullPointerException(或什么?)

java - 使用 JSON 传递对象和整数

java - MySQL连接超时