我有一个数据不断追加的文件。我正在使用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。
你可以尝试下面的代码
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){
}