Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes I/O and Streams and the fly likes RandomAccessFile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "RandomAccessFile" Watch "RandomAccessFile" New topic


Prashant Sehgal
Ranch Hand

Joined: Jun 20, 2003
Posts: 56
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

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
Prashant Sehgal
Ranch Hand

Joined: Jun 20, 2003
Posts: 56

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 ]
I agree. Here's the link:
subject: RandomAccessFile
jQuery in Action, 3rd edition