Java如何在第N行开始读取文件后具有良好的性能

问题描述 投票:0回答:1

我有一个数据不断追加的文件。我正在使用java来读取该文件并处理数据。为了获得最新的数据,我将偏移量存储到我读取文件的位置,并在下一次运行java进程时继续读取该偏移量。

RandomAccessFile f = new RandomAccessFile("file.txt","r");
f.seek(offset)

这里的问题是性能。它比BufferedReader慢大约300倍。是否可以使用BufferedReader从特定行恢复读取?

import java.io.RandomAccessFile;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {

 public static void main(String[] args) {
  RandomAccessFile objReader = null;
  try {
   String strCurrentLine;
   long startTime = System.currentTimeMillis();

   objReader = new RandomAccessFile("auditlog-2018-12-21.txt", "r");

   while ((strCurrentLine = objReader.readLine()) != null) {

   }
   System.out.println(System.currentTimeMillis()-startTime);

  } catch (Exception e) {

   e.printStackTrace();

  } finally {

   try {
    if (objReader != null)
     objReader.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
 }
}

读取具有100,000行的30M文件需要12秒,而用BufferReader替换RandomAccessFile需要不到400ms。

java bufferedreader file-read randomaccessfile
1个回答
0
投票

你可以尝试下面的代码

try {
    BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"), StandardCharsets.UTF_8);
    List<String> line = reader.lines().skip(31).limit(1).collect(Collectors.toList());
    line.stream().forEach(System.out::println);
    }catch(Exception e){

    }
© www.soinside.com 2019 - 2024. All rights reserved.