【发布时间】: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