• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile

 
Prashant Sehgal
Ranch Hand
Posts: 56
  • 0
  • 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?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • 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
  • 0
  • 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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic