Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

RandomAccessFile

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although we can seek N bytes in a RandomAccessFile and read/write at the N+1 bytes, can we also do the same with lines? Can we skip the N lines and read/write directly at the (N+1)th line?

I know we can use the readLine() method and keep a count of how many lines we have read, uptill the point count reaches N. But then that's not really Random Access, is it?

How can say something like raf.seekLine(100) and directly reach the 100th line?

Is there a way?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No - because in order to know how many lines there are, something needs to look at each character along the way to see if it's a \r or \n. Without knowing where each line boundary is, there's no way to know what the line count is, or where each line begins. You could write a class which does this work for you, making it look like you're getting random access, but you still need to read all the bytes up to line n, at least once.
 
Prashant Sehgal
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm.

I built myself a custom class that indexes the new lines in a file according to byte position.

Just call and it returns a long that gives the byte position of that line in the file. Then you can use your RandomAccessFile object to seek that byte position. Here's the code for ByteInderxer:


[ May 14, 2004: Message edited by: Prashant Sehgal ]
 
    Bookmark Topic Watch Topic
  • New Topic