首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用java从大文件中分块读取

使用java从大文件中分块读取
EN

Stack Overflow用户
提问于 2015-04-29 03:05:42
回答 1查看 440关注 0票数 1

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

我想把它以1000个实体的块来列出。

我试过了:

代码语言:javascript
运行
复制
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;
}

我有这个文件:

代码语言:javascript
运行
复制
11
22
33
..
100100

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

(chunkSize为2行,currentSeekPosition = 4)

我该如何解决这个问题呢?

EN

回答 1

Stack Overflow用户

发布于 2015-04-29 03:39:23

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

代码语言:javascript
运行
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29927814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档