• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Seek and Read specific line of a file

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jim.
 
reply
    Bookmark Topic Watch Topic
  • New Topic