[英]How to read large .txt file in chunks of 1000 lines
我想從文件中重復讀取和處理 1000 行塊,直到文件結束。
Path pp = FileSystems.getDefault().getPath("logs", "access.log");
final int BUFFER_SIZE = 1024*1024; //this is actually bytes
FileInputStream fis = new FileInputStream(pp.toFile());
byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
while( ( read = fis.read( buffer ) ) > 0 ){
// call your other methodes here...
}
fis.close();
多年來,我面臨着同樣的情況。 我的最終解決方案是使用接口 List 中的.sublist()
方法,您可以使用它:
第一步:讀取給定文件中的所有行
String textfileRow = null;
List<String> fileLines = new ArrayList<String>();
BufferedReader fileContentBuffer = null;
fileContentBuffer = new BufferedReader(new FileReader(<your file>));
while ((textfileRow = fileContentBuffer.readLine()) != null)
{
fileLines.add(textfileRow);
}
第二步:從先前創建的列表中以給定的大小創建塊
int final CHUNKSIZE = <your needed chunk size>;
int lineIndex = 0;
while (lineIndex < fileLines.size())
{
int chunkEnd = lineIndex + CHUNKSIZE;
if (chunkEnd >= fileLines.size())
{
chunkEnd = fileLines.size();
}
List<Type you need> mySubList = fileLines.subList(lineIndex, chunkEnd);
//What ever you want do to...
lineIndex = chunkEnd;
}
在我的項目中,我將它與最多 20k 行的 csv 文件一起使用,並且效果很好。
編輯:我在標題中看到有一個對文本文件的請求,所以我改變了讀取文本文件的方式。
舊方法:使用BufferedReader的readLine方法而不是原始FileInputStream
。
Path path = // access your path...;
List<String> buffer = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader(path.toFile))) {
String nextLine;
do {
buffer.clear();
for (int i=0; i < chunkSize; i++) {
// note that in.readLine() returns null at end-of-file
if ((nextLine = in.readLine()) == null) break;
buffer.add(next);
}
processChunk(buffer); // note size may be less than desiredChunkSize
} while (nextLine != null);
} catch (IOException ioe) {
// handle exceptions here
}
// all resources will be automatically closed before this line is reached
較新的方法:使用Files.lines訪問延遲填充的行流:
Path path = // access your path...;
final AtomicInteger c = new AtomicInteger();
Files.lines(path)
.collect(Collectors.groupingBy(e -> c.getAndIncrement()/chunkSize))
.forEach(chunk -> processChunk(chunk));
// all resources will be automatically closed before this line is reached
免責聲明:我也沒有測試過; 但兩種方法都應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.