繁体   English   中英

如何以 1000 行的块读取大型 .txt 文件

[英]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 文件一起使用,并且效果很好。

编辑:我在标题中看到有一个对文本文件的请求,所以我改变了读取文本文件的方式。

旧方法:使用BufferedReaderreadLine方法而不是原始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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM