-3

I want to read a file line by file to a specified seek position. It is easy to start reading from a certain seek position and read further till end.

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

This set file reading position to given seek and start reading till that. How to read from the first line, line by line and stop reading ahead or seek position?

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
  • If you know about [`seek(long pos)`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#seek-long-), how can you not know about [`getFilePointer()`](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html#getFilePointer--)? Keep reading until you reach the desired position!! – Andreas Mar 10 '19 at 05:35
  • By "ahead or seek position", do you mean prior to reading the line that spans that position? Are you expecting Java to be clairvoyant and know ahead of time about what it hasn't read yet? If you want to know how to know when you have read past that position, then @Andreas seems to have your answer. – CryptoFool Mar 10 '19 at 05:37
  • @Andreas What if I keep reading a new line it exceeds the seek value? – Shashwat Kumar Mar 10 '19 at 05:39
  • @ShashwatKumar That's for *you* to decide what it means if the specific seek position is in the middle of a line. – Andreas Mar 10 '19 at 05:40

1 Answers1

0

To get the current seek position, use getFilePointer().

Read the final line that crosses the seek position, and then throw it away. You can remember the seek position prior to reading each line, and then if you want to seek back to before the seek position after throwing away the last line, you can do so.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44