简体   繁体   中英

How to “peek” with randomAccessFile?

I have this code to check if a log line is sent at some time. Problem is that the file-pointer exceeds even if the log line is not from the time I wanted (say "later" then the search for time). I want to increment the file-pointer only if the line was eventually taken to the answer List<String>

@Override
public List<String> getForMinuteTimeFrame(LocalTime currentTime) {
    List<String> lines = new ArrayList<>();
    String line = null;
    while ((line = randomAccessFile.readLine()) != null) {
        if (fetchTime(line).isEqual(currentTime)) {
            lines.add(line);
        }
    }
    return lines;
}

How can I do this elegantly? Input file is very big (~250 MB), so I read line by line.

You should be able to get the current file point using "randomAccessFile.getFilePointer()", and store that each time you successfully read a line you care about. Then before you return, you can set the current file position back to that location using randomAccessFile.seek(), passing the value you got from getFilePointer(). This will restore the read point back to what it was before the last line(s) were read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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