• Post Reply Bookmark Topic Watch Topic
  • New Topic

Seek and Read specific line of a file  RSS feed

 
Chris Ramsey
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
Does anyone know an efficient way to find the beginning positions of each line in a file? I want to use the RandomAccessFile.seek(position) to go to the beginning of a specified line and read it. I am using it like a paging utility to show the contents of a line on a page. Thanks.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only way to find out where lines begin in a file is by reading through the file from the beginning, at least once. That's because there's no way of knowing in advance which bytes will represent '\r' or '\n' - you've got to check them all. (Or, all up to whatever line number you're interested in.) Now if you're going to refer to one file repeatedly, there are things you can do to make subsequent line lookup much easier. The simplest is to use a BufferedReader to read lines with readLine(), and create a List of Strings containing all the lines read. If the file is big and you don't have enough memory, you could create some sort of index instead, e.g. showing where each line begins, or every 100 lines, something like that. This is a bit complex though - stick with the List of Strings idea if you can.
 
Chris Ramsey
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!