1) read the line that the user selects
If you need to read a line selected by the user only once or several times (or if the file is small enough), you just need to read the file line by line from the very beginning until you reach the selected line.
If, on the other hand, you often need to read a line selected by the user, you must create an index of line numbers and offsets. So, for example, line 42 corresponds to an offset of 2347 bytes per file. Ideally, then you would only read the entire file once and save the index - for example, on a map, using line numbers as keys and offsets as values.
2) read new lines added since last read. I plan to read the file every 10 seconds. I have the number of lines and find out the new line numbers, but I need to read this line
At the second point, you can simply save the current offset to a file instead of saving the current line number, but, of course, it will not hurt to continue building the index if it continues to have a significant performance advantage.
- Use RandomAccessFile.seek (long offset) to set the file pointer to the last saved offset (confirm that the file is longer than the most recently stored offset, if not, nothing new has been added).
- Use RandomAccessFile.readLine () to read a line of a file
- Call RandomAccessFile.getFilePointer () to get the current offset after reading the line and optionally put (currLineNo + 1, offset) in the index.
- Repeat steps 2-3 until the end of the file is reached.
But don't get too carried away with optimizing performance if performance is not a problem or is likely to be a problem.
source share